<?php

namespace app\admin\controller;

use app\models\{Signexcel, Zhaopai, Wenjian, Userstatus, Kaoke, Leave, Dingorxuan, Sign, Signlog, Uploadtk, Admin, Business, Businessxq, Message as Messages, PlatClass, Goods, GoodsSpec, Region, User as Users, Order, OrderGoods, BussinessLog, Opend, Message, Reimburs, ReimbursLog};
use think\Db;
use app\facade\Redis;
use think\Validate;
use think\facade\Debug;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;

class Shop extends Base
{

    public function signexcel_edit()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require|in:2,3',
            ], [
                'id.require' => 'id不能为空',
                'status.require' => '状态不能为空',
                'status.in' => '状态类型不正确',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $res = (new Signexcel())->where('id', $data['id'])->update(['status' => $data['status']]);
            if ($res) {
                return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['status' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Signexcel();
            $id = $this->request->get('id/d', 0);
            $rowlsm = $model->where('id', $id)->find();
            if ($rowlsm) {
                $olddata = json_decode($rowlsm['olddata'], true) ?? [];
                $time = strtotime($rowlsm['yeardays']);
                foreach ($olddata as $k => &$row) {
                    $row['orderid'] = $row['orderid'] ?? 0;
                    $row['kuayue'] = '';
                    $mianji = '';
                    if (!empty($row['orderid'])) {
                        $weikuan = '';
                        $address = '';
                        $business = (new Business())->where(['id' => $row['orderid']])->select();
                        foreach ($business as $bus) {
                            preg_match('/(.*?(省|自治区|特别行政区|市))?(.*?(市|自治州|地区|盟|区划))?(.*?(区|县|旗|市))/', $bus['areas'], $matches);
                            $bus['areas'] = ($matches[3] ?? '') . ($matches[5] ?? '');
                            $wk = '';
                            switch ($bus['weikuan']) {
                                case '1':
                                    $wk = '未回款';
                                    break;
                                case '2':
                                    $wk = '部分回款';
                                    break;
                                case '3':
                                    $wk = '全部回款';
                                    break;
                                default:
                                    $wk = '未知';
                                    break;
                            }
                            if ($bus['weikuanstatus'] == 2) {
                                $wk = $wk . '(待审核)';
                            }
                            if (empty($weikuan)) {
                                $weikuan = $wk;
                            } else {
                                $weikuan = $weikuan . '、' . $wk;
                            }
                            if (empty($address)) {
                                $address = $bus['areas'];
                            } else {
                                $address = $address . '、' . $bus['areas'];
                            }
                            if (empty($mianji)) {
                                $fg = '';
                            } else {
                                $fg = '、';
                            }
                            if ($bus['ordertype'] != 2 && $bus['ordertype'] != 12) {
                                if (!empty($bus['mianji']) && $bus['mianji'] == 2) {
                                    $mianji = $mianji . $fg . '60-79m²';
                                }
                                if (!empty($bus['mianji']) && $bus['mianji'] == 3) {
                                    $mianji = $mianji . $fg . '80m²及以上';
                                }
                            }
                        }
                        $row['areas'] = $mianji;
                        $row['address2'] = $address;
                        $row['weikuan'] = $weikuan;
                    }
                    if ($k == 0 && !empty($row['orderid'])) {
                        $yearssign = (new Sign())->where(['user_id' => $rowlsm['user_id'], 'orderid' => $row['orderid'], 'years' => date('Ym', strtotime("-1 month", $time))])->find();
                        if (!empty($yearssign)) {
                            $row['kuayue'] = '是';
                        }
                    }
                }
                $rowlsm['olddata'] = $olddata;
                $newdata = json_decode($rowlsm['newdata'], true) ?? [];
                foreach ($newdata as $k => &$row) {
                    $row['orderid'] = $row['orderid'] ?? 0;
                    $row['kuayue'] = '';
                    $mianji = '';
                    if (!empty($row['orderid'])) {
                        $weikuan = '';
                        $address = '';
                        $business = (new Business())->where(['id' => $row['orderid']])->select();
                        foreach ($business as $bus) {
                            preg_match('/(.*?(省|自治区|特别行政区|市))?(.*?(市|自治州|地区|盟|区划))?(.*?(区|县|旗|市))/', $bus['areas'], $matches);
                            $bus['areas'] = ($matches[3] ?? '') . ($matches[5] ?? '');
                            $wk = '';
                            switch ($bus['weikuan']) {
                                case '1':
                                    $wk = '未回款';
                                    break;
                                case '2':
                                    $wk = '部分回款';
                                    break;
                                case '3':
                                    $wk = '全部回款';
                                    break;
                                default:
                                    $wk = '未知';
                                    break;
                            }
                            if ($bus['weikuanstatus'] == 2) {
                                $wk = $wk . '(待审核)';
                            }
                            if (empty($weikuan)) {
                                $weikuan = $wk;
                            } else {
                                $weikuan = $weikuan . '、' . $wk;
                            }
                            if (empty($address)) {
                                $address = $bus['areas'];
                            } else {
                                $address = $address . '、' . $bus['areas'];
                            }
                            if ($bus['ordertype'] != 2 && $bus['ordertype'] != 12) {
                                if (!empty($bus['mianji']) && $bus['mianji'] == 2) {
                                    $mianji = $mianji . $fg . '60-79m²';
                                }
                                if (!empty($bus['mianji']) && $bus['mianji'] == 3) {
                                    $mianji = $mianji . $fg . '80m²及以上';
                                }
                            }
                        }
                        $row['address2'] = $address;
                        $row['weikuan'] = $weikuan;
                    }
                    $row['areas'] = $mianji;
                    if ($k == 0 && !empty($row['orderid'])) {
                        $yearssign = (new Sign())->where(['user_id' => $rowlsm['user_id'], 'orderid' => $row['orderid'], 'years' => date('Ym', strtotime("-1 month", $time))])->find();
                        if (!empty($yearssign)) {
                            $row['kuayue'] = '是';
                        }
                    }
                }
                $rowlsm['newdata'] = $newdata;
            }
            return view('', [
                'row' => $rowlsm,
            ]);
        }
    }

    public function signexcel()
    {
        $list = (new Signexcel())->alias('s')->leftjoin('user u', 'u.id = s.user_id')->field('s.*')->order('s.yeardays desc');
        $data = $this->request->get();
        $list->where(['s.status' => [1, 2, 3]]);
        if (!empty($data['status'])) {
            $list = $list->where('s.status', $data['status']);
        }
        if (!empty($data['type'])) {
            if ($data['type'] == 1) {
                $list = $list->where(['u.type' => 2, 'u.sonstype' => 1]);
            }
            if ($data['type'] == 2) {
                $list = $list->where(['u.type' => 2, 'u.sonstype' => 2]);
            }
        }
        if (!empty($data['userid'])) {
            $list = $list->where('s.user_id', $data['userid']);
        }
        $list = $list->field('s.*,u.account as dudao,u.type as dudao_type')->paginate(10, false, ['query' => $this->request->param()]);
        $status_text = [
            0 => '未修改',
            1 => '待审核',
            2 => '审核通过',
            3 => '审核驳回',
        ];
        foreach ($list as $result) {
            $result['status_text'] = $status_text[$result['status']] ?? [];
            // $dudao = (new Users())->where('id', $result['user_id'])->find() ?? [];
            // $result['dudao'] = $dudao['account'] ?? '';
            // $result['dudao_type'] = $dudao['type'] ?? 0;
        }
        $dudao = (new Users())->where(['type' => 2, 'del' => 1])->select();
        return view(null, [
            'dudao' => $dudao,
            'list' => $list
        ]);
    }

    public function bicloselist()
    {
        $list = (new Zhaopai())->alias('d')->field('d.*')->leftjoin('business b', 'd.orderid = b.id')->order('d.id desc');
        $data = $this->request->get();
        if (!empty($data['status'])) {
            $list = $list->where('d.status', $data['status']);
        }
        if (!empty($data['orderid'])) {
            $list = $list->where('d.orderid', $data['orderid']);
        }
        if (!empty($data['userid'])) {
            $list = $list->where('d.user_id', $data['userid']);
        }
        if (!empty($data['title'])) {
            $list = $list->where('b.areas|b.title|b.address|b.phone|b.mobile|b.phone2|b.name2|b.getaddress|b.name|b.province|b.city|b.area', 'like', '%' . $data['title'] . '%');
        }
        $list = $list->paginate(5, false, ['query' => $this->request->param()]);
        foreach ($list as $result) {
            $result['dudao'] = (new Users())->where('id', $result['user_id'])->value('account') ?? '';
            $result['images'] = json_decode($result['images'], true);
        }
        $dudao = (new Users())->where(['type' => 2, 'del' => 1])->select();
        return view(null, [
            'dudao' => $dudao,
            'list' => $list
        ]);
    }

    public function ajaxtips()
    {
        $menus = config('menu.menu')['shop'] ?? '';
        $list = [];
        foreach ($menus['sub'] as $key => $menu) {
            if (!empty($menu['tips'])) {
                switch ($key) {
                    case 'shoplists':
                        $business = (new Business())->where('isshenhe', 2)->where(['status' => [1, 2, 3, 5]])->count();
                        if ($business > 0) {
                            $list[] = $key;
                        }
                        # code...
                        break;
                    case 'wkshoplists':
                        $business = (new Business())->where('weikuanstatus', 2)->where(['status' => [1, 2, 3, 5]])->count();
                        if ($business > 0) {
                            $list[] = $key;
                        }
                        # code...
                        break;
                    case 'djqrshoplists':
                        $business = (new Business())->where('qktype', 1)->where('qkqueren', 1)->where(['status' => [1, 2, 3, 5]])->count();
                        if ($business > 0) {
                            $list[] = $key;
                        }
                        break;
                    case 'dingorxuan':
                        $business = (new Dingorxuan())->where('status', 1)->count();
                        if ($business > 0) {
                            $list[] = $key;
                        }
                        break;
                    case 'bicloselist':
                        $business = (new Zhaopai())->where('status', 1)->count();
                        if ($business > 0) {
                            $list[] = $key;
                        }
                        break;
                    default:
                        # code...
                        break;
                }
            }
        }
        return json(['status' => 0, 'data' => $list, 'msg' => '获取成功']);
    }

    public function user_status()
    {
        $data = $this->request->post();
        if (empty($data['status'])) {
            return json(['status' => 1, 'data' => [], 'msg' => '状态码错误']);
        }
        if (empty($data['id'])) {
            return json(['status' => 1, 'data' => [], 'msg' => '用户ID错误']);
        }
        $order = (new Userstatus())->order('created desc')->where(['orderid' => 0, 'user_id' => $data['id'], 'type' => 2])->find();
        Db::startTrans();
        try {
            if (!empty($order)) {
                (new Userstatus())->allowfield(true)->save(['type' => 1], ['id' => $order['id']]);
            }
            $userstatus =  (new Userstatus())->order('id desc')->where(['type' => 2, 'user_id' => $data['id']])->value('status') ?? 2;
            (new Users())->where('id', $data['id'])->update(['status' => $userstatus]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 1, 'data' => [], 'msg' => $e->getMessage()]);
        }
        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
    }

    public function user_status1()
    {
        $data = $this->request->post();
        if (empty($data['status'])) {
            return json(['status' => 1, 'data' => [], 'msg' => '状态码错误']);
        }
        if (empty($data['id'])) {
            return json(['status' => 1, 'data' => [], 'msg' => '用户ID错误']);
        }
        Db::startTrans();
        try {
            (new Users())->where('id', $data['id'])->update(['fangjia' => $data['status']]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 1, 'data' => [], 'msg' => $e->getMessage()]);
        }
        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
    }

    public function wenjian()
    {
        $list = (new Wenjian())->order('updated desc');
        $data = $this->request->get();
        if (!empty($data['userid'])) {
            $list = $list->where('user_id', $data['userid']);
        }
        if (empty($data['isshow'])) {
            $date = date('Y-m') . '-01';
            $list = $list->where('created', '>= time', $date);
        }
        if (!empty($data['title'])) {
            $list = $list->where('title', 'like', '%' . $data['title'] . '%');
        }
        $list = $list->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $result) {
            $result['dudao'] = (new Users())->where('id', $result['user_id'])->value('account') ?? '';
            $result['url'] = json_decode($result['url'], true);
        }
        $dudao = (new Users())->where(['type' => 2, 'del' => 1])->select();
        return view(null, [
            'dudao' => $dudao,
            'list' => $list
        ]);
    }

    public function Kaoke()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'data' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'gt.require' => 'ID必须大于0',
                'data.require' => '数据不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $json = json_encode($data['data'], true);
            $res = (new Users())->where('id', $data['id'])->update(['kaoke' => $json]);
            if ($res) {
                return json(['status' => 0, 'data' => [], 'msg' => '保存成功']);
            }
            return json(['status' => 1, 'data' => [], 'msg' => '保存失败，请重试']);
        } else {
            $id = $this->request->get('id/d', 0);
            $typearr = [
                ['type' => 1, 'name' => '专业知识与技能(20分)', 'data' => []],
                ['type' => 2, 'name' => '业务技能(25分)', 'data' => []],
                ['type' => 3, 'name' => '品质与态度(20分)', 'data' => []],
                ['type' => 4, 'name' => '工作绩效(35分)', 'data' => []],
            ];
            foreach ($typearr as &$arr) {
                $arr['data'] = (new Kaoke())->where(['type' => $arr['type']])->select();
            }
            $user = (new Users())->where('id', $id)->value('kaoke') ?? '';
            $user = json_decode($user, true);
            return view(null, [
                'list' => $typearr,
                'id' => $id,
                'user' => $user
            ]);
        }
    }

    public function leavelist()
    {
        $data = $this->request->get();
        $list = (new Leave())->order(['id' => 'desc']);
        if (!empty($data['user_id'])) {
            $list = $list->where('user_id', $data['user_id']);
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        if (!empty($data['type'])) {
            $list = $list->where('type', $data['type']);
        }
        if (!empty($data['dates'])) {
            $yearday = date('Y-m-d', strtotime($data['dates']));
            $list = $list->whereTime('startime', '<=', $yearday)
                ->whereTime('endtime', '>=', $yearday);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()]);
        foreach ($list as $result) {
            $result['user_name'] = (new Users())->where(['id' => $result['user_id']])->value('account') ?? '';
        }
        return view(null, [
            'dlist' => (new Users())->where(['type' => 2, 'del' => 1])->select(),
            'list' => $list
        ]);
    }


    public function leavestatus()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'status' => 'require',
        ], [
            'id.require' => 'ID不能为空',
            'status.require' => '状态不能为空',
        ]);
        if (!$validate->check($data)) {
            return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
        }
        $order = (new Leave())->where(['id' => $data['id']])->find();
        if (empty($order)) {
            return json(['status' => 1, 'data' => [], 'msg' => '记录不存在']);
        }
        if ($order['status'] != 1) {
            return json(['status' => 1, 'data' => [], 'msg' => '记录不属于操作状态']);
        }
        $text = '请假申请审批通过,请前往我的请假查看具体信息';
        if ($data['status'] == 3) {
            $text = '请假申请审批驳回!';
        }
        Db::startTrans();
        try {
            (new Leave())->allowfield(true)->save(['status' => $data['status']], ['id' => $order['id']]);
            if ($data['status'] == 3) {
                (new Message())->allowfield(true)->save([
                    'type' => 1,
                    'orderid' => 0,
                    'user_id' =>  $order['user_id'],
                    'ouser_id' => 0,
                    'status' => 0,
                    'endstatus' => 0,
                    'text' => $text,
                    'yue' => 2
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 1, 'data' => [], 'msg' => $e->getMessage()]);
        }
        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
    }


    public function bicloselist_status()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $dingorxuan = (new Zhaopai())->where(['id' => $data['id']])->find();
            if (empty($dingorxuan)) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单不存在']);
            }
            if ($dingorxuan['status'] != 1) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单已审核']);
            }
            $business = (new Zhaopai())->where(['id' => $dingorxuan['orderid']])->find();
            switch ($data['status']) {
                case '2':
                    if (empty($business)) {
                        return json(['status' => 1, 'data' => [], 'msg' => '关联订单不存在']);
                    }
                    Db::startTrans();
                    try {
                        (new Message())->allowfield(true)->save([
                            'type' => 1,
                            'orderid' => $dingorxuan['orderid'],
                            'user_id' =>  $dingorxuan['user_id'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 0,
                            'text' => '闭店调查审核通过!',
                            'yue' => 2
                        ]);
                        (new Business())->where(['id' => $dingorxuan['orderid']])->update(['schedule' => 9, 'status' => 5, 'bicloses' => 5]);
                        (new Zhaopai())->where(['id' => $data['id']])->update(['status' => $data['status']]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    break;
                case '3':
                    Db::startTrans();
                    try {
                        (new Message())->allowfield(true)->save([
                            'type' => 1,
                            'orderid' => $dingorxuan['orderid'],
                            'user_id' =>  $dingorxuan['user_id'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 0,
                            'text' => '闭店调查驳回,' . $data['value'] ?? '',
                            'yue' => 2
                        ]);
                        (new Business())->where(['id' => $dingorxuan['orderid']])->update(['bicloses' => 2]);
                        (new Zhaopai())->where(['id' => $data['id']])->update(['status' => $data['status'], 'text' => $data['value'] ?? '']);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    break;
                default:
                    return json(['status' => 1, 'data' => [], 'msg' => '状态错误']);
                    break;
            }
            return json(['status' => 1, 'data' => [], 'msg' => '操作失败']);
        }
    }

    public function dingorxuan_status()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $dingorxuan = (new Dingorxuan())->where(['id' => $data['id']])->find();
            if (empty($dingorxuan)) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单不存在']);
            }
            if ($dingorxuan['status'] != 1) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单已审核']);
            }
            $business = (new Business())->where(['id' => $dingorxuan['orderid']])->find();
            switch ($data['status']) {
                case '2':
                    if (empty($business)) {
                        return json(['status' => 1, 'data' => [], 'msg' => '关联订单不存在']);
                    }
                    //if ($business['ordertype'] != 2 && $business['ordertype'] != 12) {
                    //return json(['status' => 1, 'data' => [], 'msg' => '关联订单非定店类型']);
                    //}
                    if ($business['ordertype'] == 1) {
                        return json(['status' => 1, 'data' => [], 'msg' => '关联订单已经是首选址类型']);
                    }
                    Db::startTrans();
                    try {
                        (new Message())->allowfield(true)->save([
                            'type' => 1,
                            'orderid' => $dingorxuan['orderid'],
                            'user_id' =>  $dingorxuan['user_id'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 0,
                            'text' => '定店转选址审核通过!',
                            'yue' => 2
                        ]);
                        if ($business['ordertype'] == 2 || $business['ordertype'] == 12) {
                            (new Business())->where(['id' => $dingorxuan['orderid']])->update(['ordertype' => 1]);
                        }
                        (new Dingorxuan())->where(['id' => $data['id']])->update(['status' => $data['status'], 'endstatus' => 1]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    break;
                case '9':
                    if (empty($business)) {
                        return json(['status' => 1, 'data' => [], 'msg' => '关联订单不存在']);
                    }
                    // if ($business['ordertype'] != 2 && $business['ordertype'] != 12) {
                    //     return json(['status' => 1, 'data' => [], 'msg' => '关联订单非定店类型']);
                    // }
                    if ($business['ordertype'] == 11) {
                        return json(['status' => 1, 'data' => [], 'msg' => '关联订单已经是二次选址类型']);
                    }
                    Db::startTrans();
                    try {
                        (new Message())->allowfield(true)->save([
                            'type' => 1,
                            'orderid' => $dingorxuan['orderid'],
                            'user_id' =>  $dingorxuan['user_id'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 0,
                            'text' => '定店转选址审核通过!',
                            'yue' => 2
                        ]);
                        if ($business['ordertype'] == 2 || $business['ordertype'] == 12) {
                            (new Business())->where(['id' => $dingorxuan['orderid']])->update(['ordertype' => 11]);
                        }
                        (new Dingorxuan())->where(['id' => $data['id']])->update(['status' => 2, 'endstatus' => 11]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    break;
                case '3':
                    Db::startTrans();
                    try {
                        (new Message())->allowfield(true)->save([
                            'type' => 1,
                            'orderid' => $dingorxuan['orderid'],
                            'user_id' =>  $dingorxuan['user_id'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 0,
                            'text' => '定转选驳回,' . $data['value'] ?? '',
                            'yue' => 2
                        ]);
                        (new Dingorxuan())->where(['id' => $data['id']])->update(['status' => $data['status'], 'text' => $data['value'] ?? '']);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    break;
                default:
                    return json(['status' => 1, 'data' => [], 'msg' => '状态错误']);
                    break;
            }
            return json(['status' => 1, 'data' => [], 'msg' => '操作失败']);
        }
    }

    public function dingorxuan()
    {
        $list = (new Dingorxuan())->alias('d')->field('d.*')->leftjoin('business b', 'd.orderid = b.id')->order('id desc');
        $data = $this->request->get();
        if (!empty($data['status'])) {
            $list = $list->where('d.status', $data['status']);
        }
        if (!empty($data['orderid'])) {
            $list = $list->where('d.orderid', $data['orderid']);
        }
        if (!empty($data['userid'])) {
            $list = $list->where('d.user_id', $data['userid']);
        }
        if (!empty($data['title'])) {
            $list = $list->where('b.areas|b.title|b.address|b.phone|b.mobile|b.phone2|b.name2|b.getaddress|b.name|b.province|b.city|b.area', 'like', '%' . $data['title'] . '%');
        }
        $list = $list->paginate(5, false, ['query' => $this->request->param()]);
        foreach ($list as $result) {
            $result['dudao'] = (new Users())->where('id', $result['user_id'])->value('account') ?? '';
            $result['datas'] = json_decode($result['datas'], true);
        }
        $dudao = (new Users())->where(['type' => 2, 'del' => 1])->select();
        return view(null, [
            'dudao' => $dudao,
            'list' => $list
        ]);
    }

    public function usersign()
    {
        $list = (new Sign())->order('yearday desc');
        $data = $this->request->get();
        if (!empty($data['id'])) {
            $list = $list->where('user_id', $data['id']);
        }
        if (!empty($data['dates'])) {
            $years = date('Ym', strtotime($data['dates']));
            $list = $list->where('years', $years);
        } else {
            // $years = date('Ym', strtotime("-1 month"));
            $years = date('Ym', time());
            $list = $list->where('years', $years);
        }
        $list = $list->paginate(31, false, ['query' => $this->request->param()]);
        foreach ($list as $result) {
        }
        return view(null, [
            'list' => $list
        ]);
    }


    public function usersigndetailall()
    {
        $data = $this->request->get();
        $list = (new Signlog())->order(['created' => 'desc', 'yearday' => 'desc', 'id' => 'desc']);
        if (!empty($data['user_id'])) {
            $list = $list->where('user_id', $data['user_id']);
        }
        if (!empty($data['buka'])) {
            if ($data['buka'] == 99) {
                $list = $list->where('lianxu', 2);
            } elseif ($data['buka'] == 100) {
                $list = $list->where('type', 2)->where(['orderid' => [0, '', NULL, null, 'null', 'NULL']]);
            } else {
                $list = $list->where('buka', $data['buka']);
            }
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        if (!empty($data['monoraft'])) {
            $list = $list->where('monoraft', $data['monoraft']);
        }
        if (!empty($data['type'])) {
            $list = $list->where('type', $data['type']);
        }
        if (!empty($data['dates'])) {
            $yearday = date('Ymd', strtotime($data['dates']));
            $list = $list->where('yearday', $yearday);
        } else {
            // $yearday = date('Ymd');
            // $list = $list->where('yearday', $yearday);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()]);
        foreach ($list as $result) {
            $result['images'] = json_decode($result['images'], true);
            $result['user_name'] = (new Users())->where(['id' => $result['user_id']])->value('account') ?? '';
            if ($result['lianxu'] == 2) {
                $result['user_name'] = $result['user_name'] . '(含打卡超7天任务)';
            }
        }
        return view(null, [
            'dlist' => (new Users())->where(['type' => 2, 'del' => 1])->select(),
            'list' => $list
        ]);
    }


    public function signwei()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'status' => 'require',
        ], [
            'id.require' => 'ID不能为空',
            'status.require' => '状态不能为空',
        ]);
        if (!$validate->check($data)) {
            return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
        }
        $order = (new Signlog())->where(['id' => $data['id']])->find();
        if (empty($order)) {
            return json(['status' => 1, 'data' => [], 'msg' => '打卡记录不存在不存在']);
        }
        $sign = (new Sign())->where(['user_id' => $order['user_id'], 'yearday' => $order['yearday']])->find();
        if ($order['monoraft'] == 1) {
            $fileds = 'monwei';
            $text = $order['yearday'] . '上班考勤照片被标记违规';
        } else {
            $fileds = 'afterwei';
            $text = $order['yearday'] . '下班考勤照片被标记违规';
        }
        Db::startTrans();
        try {
            (new Signlog())->allowfield(true)->save(['iswei' => $data['status']], ['id' => $order['id']]);
            //查找是否还有违规
            $weicount = (new Signlog())->where(['user_id' => $order['user_id'], 'iswei' => 2, 'yearday' => $order['yearday'], 'monoraft' => $order['monoraft']])->count();
            $iswei = $weicount > 0 ? 2 : 1;
            if ($iswei != $sign[$fileds]) {
                (new Sign())->allowfield(true)->save([$fileds => $iswei], ['id' => $sign['id']]);
            }
            if ($iswei == 2) {
                (new Message())->allowfield(true)->save([
                    'type' => 1,
                    'orderid' => 0,
                    'user_id' =>  $order['user_id'],
                    'ouser_id' => 0,
                    'status' => 0,
                    'endstatus' => 0,
                    'text' => $text,
                    'yue' => 2
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 1, 'data' => [], 'msg' => $e->getMessage()]);
        }
        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
    }

    public function postsignstatus()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'status' => 'require',
        ], [
            'id.require' => 'ID不能为空',
            'status.require' => '状态不能为空',
        ]);
        if (!$validate->check($data)) {
            return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
        }
        $order = (new Signlog())->where(['id' => $data['id']])->find();
        if (empty($order)) {
            return json(['status' => 1, 'data' => [], 'msg' => '打卡记录不存在不存在']);
        }
        if ($order['status'] != 1) {
            return json(['status' => 1, 'data' => [], 'msg' => '打卡记录不属于操作状态']);
        }
        $post = [];
        if ($data['status'] == 2) {
            $sign = (new Sign())->where(['user_id' => $order['user_id'], 'yearday' => $order['yearday']])->find();
            if (!empty($sign)) {
                if ($order['monoraft'] == 1 && $sign['monstar'] == 2) {
                    return json(['status' => 1, 'data' => [], 'msg' => '上班卡已存在，请撤回或取消此次补卡']);
                }
                if ($order['monoraft'] == 2 && $sign['aftstar'] == 2) {
                    return json(['status' => 1, 'data' => [], 'msg' => '下班卡已存在，请撤回或取消此次补卡']);
                }
            }
            //上班卡
            if ($order['monoraft'] == 1) {
                $post['monstar'] = 2;
                $post['month_time'] = date('Y-m-d H:i:s');
            }
            //下班卡
            if ($order['monoraft'] == 2) {
                $post['aftstar'] = 2;
                $post['after_time'] = date('Y-m-d H:i:s');
            }
            $post['user_id'] = $order['user_id'] ?? 0;
            $post['orderid'] = $order['orderid'] ?? 0;
            $post['lat'] = $order['lat'] ?? 0;
            $post['lng'] = $order['lng'] ?? 0;
            $post['years'] = $order['years'] ?? 0;
            $post['yearday'] = $order['yearday'] ?? 0;
            $post['btaddress'] = $order['btaddress'] ?? '';
            $post['btname'] = $order['btname'] ?? '';
            $post['texts'] = $order['texts'] ?? '';
            $addresstext = '';
            if ($post['lat'] > 0 && $post['lng'] > 0) {
                $url = 'https://restapi.amap.com/v3/geocode/regeo';
                try {
                    $res = api_curl($url, ['location' => $post['lng'] . ',' . $post['lat'], 'key' => 'c400abfe779387dc8ded64d7db8dbbac', 'extensions' => 'base']);
                    if (!empty($res['regeocode']['addressComponent'])) {
                        if (empty($res['regeocode']['addressComponent']['city']) || is_array($res['regeocode']['addressComponent']['city'])) {
                            $city = $res['regeocode']['addressComponent']['province'] ?? '';
                        } else {
                            $city = $res['regeocode']['addressComponent']['city'] ?? '';
                        }
                        if (empty($res['regeocode']['addressComponent']['district']) || is_array($res['regeocode']['addressComponent']['district'])) {
                            $street  = '';
                        } else {
                            $street = $res['regeocode']['addressComponent']['district'] ?? '';
                        }
                        $addresstext = $city . $street;
                    }
                } catch (\Exception $e) {
                }
            }
            if (!empty($addresstext)) {
                $post['addresstext'] = $addresstext;
            }
        }
        Db::startTrans();
        try {
            (new Signlog())->allowfield(true)->save(['status' => $data['status']], ['id' => $order['id']]);
            if (!empty($post)) {
                if (!empty($sign)) {
                    (new Sign())->allowfield(true)->save($post, ['id' => $sign['id']]);
                } else {
                    (new Sign())->allowfield(true)->save($post);
                }
            }
            if ($data['status'] == 3) {
                (new Message())->allowfield(true)->save([
                    'type' => 1,
                    'orderid' => 0,
                    'user_id' =>  $order['user_id'],
                    'ouser_id' => 0,
                    'status' => 1,
                    'endstatus' => 0,
                    'text' => $order['yearday'] . '打卡|补卡申请被驳回!',
                    'yue' => 2
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 1, 'data' => [], 'msg' => $e->getMessage()]);
        }
        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
    }

    public function usersigndetail()
    {
        $id = $this->request->get('id/d', 0);
        $sign = (new Sign())->where('id', $id)->find();
        if (empty($sign)) {
            return view(null, [
                'list' => []
            ]);
        }
        $list = (new Signlog())->where(['user_id' => $sign['user_id'], 'yearday' => $sign['yearday']])->order('created desc');
        $list = $list->paginate(31, false, ['query' => $this->request->param()]);
        foreach ($list as $result) {
            $result['images'] = json_decode($result['images'], true);
        }
        return view(null, [
            'list' => $list
        ]);
    }

    public function usersignexcel()
    {
        $id = $this->request->get('id');
        $ids = $this->request->get('ids');
        $dates = $this->request->get('dates');
        $title = [
            ['field' => 'name', 'width' => 13, 'title' => '督导姓名'],
            ['field' => 'date', 'width' => 13, 'title' => '日期'],
            ['field' => 'groups', 'width' => 13, 'title' => '组别'],
            // ['field' => 'dzkhlx', 'width' => 25, 'title' => '地址客户类型'],
            ['field' => 'address', 'width' => 20, 'title' => '打卡地址'],
            ['field' => 'address2', 'width' => 20, 'title' => '业务地址'],
            ['field' => 'kehuname', 'width' => 13, 'title' => '客户'],
            ['field' => 'type', 'width' => 13, 'title' => '考勤类型'],
            ['field' => 'days', 'width' => 13, 'title' => '实施天数'],
            ['field' => 'weikuan', 'width' => 13, 'title' => '回款情况'],
            ['field' => 'areas', 'width' => 13, 'title' => '面积'],
            ['field' => 'dpxx', 'width' => 40, 'title' => '店铺信息'],
            ['field' => 'weigui', 'width' => 13, 'title' => '照片违规'],
            ['field' => 'chidao', 'width' => 13, 'title' => '迟到(次)'],
            ['field' => 'zaotui', 'width' => 13, 'title' => '早退(次)'],
            ['field' => 'queka', 'width' => 13, 'title' => '缺卡(次)'],
            ['field' => 'kuanggong', 'width' => 13, 'title' => '旷工/休假(次)'],
            ['field' => 'kuayue', 'width' => 13, 'title' => '是否跨月'],
        ];
        //样式  示例：字段 time_difference 大于 0 的行，字体颜色为FF0000
        $conditions =  [
            // [
            //     'field' => 'chidao',
            //     'symbol' => 'gt',
            //     'value' => '0',
            //     'style' => [
            //         'font' => ['color' => ['rgb' => 'ff9800']]
            //     ]
            // ],
            // [
            //     'field' => 'zaotui',
            //     'symbol' => 'gt',
            //     'value' => '0',
            //     'style' => [
            //         'font' => ['color' => ['rgb' => 'ff9800']]
            //     ]
            // ],
            // [
            //     'field' => 'queka',
            //     'symbol' => 'gt',
            //     'value' => '0',
            //     'style' => [
            //         'font' => ['color' => ['rgb' => 'ff9800']]
            //     ]
            // ],
            // [
            //     'field' => 'kuanggong',
            //     'symbol' => 'gt',
            //     'value' => '0',
            //     'style' => [
            //         'font' => ['color' => ['rgb' => 'ff9800']]
            //     ]
            // ]
        ];
        //纵向合并单元格  示例：已group_sn字段分组，值相同的合并，include_field（选择字段合并），exclude_field（排除字段合并）,可选择多个
        $merge_cells  = [
            'field' => 'name', //已该字段为分组，值相同的合并
            'include_field' => ['name'], //合并选择字段
            'exclude_field' => ['date', 'address2', 'weigui', 'groups', 'dzkhlx', 'address', 'weikuan', 'kehuname', 'areas', 'dpxx', 'days', 'type', 'chidao', 'zaotui', 'queka', 'kuanggong', 'kuayue'], //合并排除字段
        ];
        $data = [];
        //查所有督导
        $user = (new Users())->where(['type' => 2, 'del' => 1]);
        if (!empty($id)) {
            $user = $user->where(['id' => $id]);
        }
        if (!empty($ids)) {
            $ids = explode(',', $ids);
            $user = $user->where(['id' => $ids]);
        }
        $user = $user->select();
        if (!empty($dates)) {
            $time = strtotime($dates);
        } else {
            $time = strtotime("-1 month");
        }
        $dudao_text = '';
        foreach ($user as $users) {
            if (empty($dudao_text)) {
                $dudao_text = $users['account'];
            } else {
                $dudao_text .= ',' . $users['account'];
            }
            $getexc = getexcels($users, $time);
            $data = array_merge($data, $getexc);
            foreach ($data as &$rows) {
                $weikuan = explode('、', $rows['weikuan']) ?? [];
                $type = explode('、', $rows['type']) ?? [];
                foreach ($weikuan as $k => $wks) {
                    $types = $type[$k] ?? '';
                    if ($wks == '全部回款' && ($types == '定店' || $types == '二次定店')) {
                        $type[$k] = '定成';
                    } elseif ($wks == '全部回款' && ($types == '首选址' || $types == '二次选址' || $types == '定或选' || $types == '定转选')) {
                        $type[$k] = '选成';
                    }
                }
                $rows['type'] = implode('、', $type);
                $rows['weikuan'] = implode('、', $weikuan);
            }
            // if (date('Ym', $time) == date('Ym')) {
            //     $days = date('d');
            // } else {
            //     $days = date('t', $time);
            // }
            // $shang = [
            //     'i' => -1,
            //     'orderid' => -1,
            //     'key' => 0, //数组下标
            //     'frist' => 0, //最早的日期
            //     'lianxu' => 0,
            //     'chidao' => 0,
            //     'zaotui' => 0,
            //     'weigui' => 0,
            //     'queka' => 0
            // ];
            // for ($i = 1; $i <= $days; $i++) {
            //     if ($i < 10) {
            //         $yearday = date('Ym', $time) . '0' . $i;
            //     } else {
            //         $yearday = date('Ym', $time) . $i;
            //     }
            //     $sign = (new Sign())->where(['user_id' => $users['id'], 'yearday' => $yearday])->find();
            //     $xiu = '';
            //     $sign['orderid'] = $sign['orderid'] ?? -1;
            //     if ($sign['orderid'] == -1) {
            //         $xiu = '休';
            //     }
            //     if ($sign['orderid'] == 0) {
            //         $nqcount = (new Signlog())->where(['user_id' => $sign['user_id'], 'yearday' => $sign['yearday'], 'type' => 2])->count();
            //         if ($nqcount <= 0) {
            //             $xiu = '内勤';
            //         } else {
            //             //上班是否外勤
            //             $sbnqcount = (new Signlog())->order('created desc')->where(['user_id' => $sign['user_id'], 'yearday' => $sign['yearday'], 'type' => 2, 'monoraft' => 1])->count();
            //             if ($sbnqcount > 0) {
            //                 $xiu = '外勤';
            //             } else {
            //                 $xiu = '内勤';
            //             }
            //             //下班是否外勤
            //             $xbnqcount = (new Signlog())->order('created desc')->where(['user_id' => $sign['user_id'], 'yearday' => $sign['yearday'], 'type' => 2, 'monoraft' => 2])->count();
            //             if ($xbnqcount > 0 && $xiu != '外勤') {
            //                 $xiu = $xiu . '/外勤';
            //             } elseif ($xiu != '内勤') {
            //                 $xiu = $xiu . '/内勤';
            //             }
            //         }
            //     }
            //     $group = 0;
            //     $groups = "";
            //     $ordertype = 0;
            //     $business = [];
            //     $reimburs = [];
            //     $mianji = '';
            //     $weikuan = '';
            //     $kehuname = '';
            //     $type = '';
            //     $dpxx = '';
            //     if (!empty($sign['orderid']) && $sign['orderid'] != -1) {
            //         $sign['orderid'] = explode(',', $sign['orderid']);
            //         $business = (new Business())->where(['id' => $sign['orderid']])->select();
            //         foreach ($business as $bus) {
            //             //查询派单次数 1 一次派单 2二次派单
            //             $pdll_text = '';
            //             if ($bus['ytypes'] == 1) {
            //                 //查询是否派单多次
            //                 $haves = 0;
            //                 $haves2 = 0;
            //                 $haves = (new Business());
            //                 if (!empty($business['phone'])) {
            //                     $haves = $haves->whereOr(function ($query) use ($business) {
            //                         $query->where('id', '<>', $business['id'])->where(['schedule' => [1, 2, 3, 4, 5, 6, 7]])->where('phone|phone2', '=', $business['phone']);
            //                     });
            //                 } else {
            //                     $haves = $haves->where('id', 0);
            //                 }
            //                 if (!empty($business['phone2'])) {
            //                     $haves = $haves->whereOr(function ($query) use ($business) {
            //                         $query->where('id', '<>', $business['id'])->where(['schedule' => [1, 2, 3, 4, 5, 6, 7]])->where('phone|phone2', '=', $business['phone2']);
            //                     });
            //                 }
            //                 $haves = $haves->count();
            //                 if (!empty($business['lat']) && !empty($business['lon'])) {
            //                     $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $business['lat'] . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $business['lat'] . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $business['lon'] . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
            //                     $haves2 = (new Biaoji())
            //                         ->where(['name' => $business['name']])
            //                         ->where('id', '<>', $business['id'])
            //                         ->field('id,' . $filed)
            //                         ->order('dist asc');
            //                     $haves2 = $haves2->having('dist <= 0.1')->count();
            //                 }
            //                 $havecount = $haves + $haves2;
            //                 if ($havecount > 0) {
            //                     $pdll_text = '一单两派';
            //                 }
            //             } else {
            //                 $pdll_text = config()["config"]['ytypes'][$bus['ytypes']] ?? '';
            //             }
            //             if (!empty($pdll_text)) {
            //                 $pdll_text = '(' . $pdll_text . ')';
            //             }
            //             if (empty($kehuname)) {
            //                 $kehuname = trim($bus['name'] ?? '') . $pdll_text;
            //             } else {
            //                 $kehuname = $kehuname . '、' . trim($bus['name'] ?? '') . $pdll_text;
            //             }
            //             $dpxx_text = config()["config"]['ytypeslist'][$bus['ytypeslist']] ?? '';
            //             if (empty($dpxx)) {
            //                 $dpxx = $dpxx_text;
            //             } else {
            //                 $dpxx = $dpxx . '、' . $dpxx_text;
            //             }
            //             $groupsname = config()["config"]['typeex'][$bus['type']] ?? '';
            //             if (empty($groups)) {
            //                 $groups = $groupsname;
            //             } else {
            //                 $groups = $groups . '、' . $groupsname;
            //             }
            //             if (empty($mianji)) {
            //                 $fg = '';
            //             } else {
            //                 $fg = '、';
            //             }
            //             //报销记录
            //             if (!empty($bus['mianji']) && $bus['mianji'] == 1) {
            //                 $mianji = $mianji . $fg . '低于60m²';
            //             }
            //             if (!empty($bus['mianji']) && $bus['mianji'] == 2) {
            //                 $mianji = $mianji . $fg . '60-79m²';
            //             }
            //             if (!empty($bus['mianji']) && $bus['mianji'] == 3) {
            //                 $mianji = $mianji . $fg . '80m²及以上';
            //             }

            //             $reimburs = (new Reimburs())->order('status desc')->where(['user_id' => $users['id'], 'orderid' => $bus['id'], 'status' => [1, 2]])->order('id desc')->find();
            //             if (!empty($reimburs)) {
            //                 $dingzhuanxuan = (new Dingorxuan())->where(['status' => 2, 'orderid' => $bus['id']])->find();
            //                 if (!empty($dingzhuanxuan)) {
            //                     $text_type10 = '定转选';
            //                 } else {
            //                     $text_type10 = trim(config()["config"]['ordertype'][$reimburs['jobtype']] ?? '');
            //                 }
            //                 if (empty($type)) {
            //                     $type = $text_type10;
            //                 } else {
            //                     $type = $type . $fg . $text_type10;
            //                 }
            //             }
            //             if (!empty($reimburs) && $reimburs['mianji'] == 4 && empty($mianji)) {
            //                 $mianji = $mianji . $fg . '低于60m²';
            //             }
            //             if (!empty($reimburs) && $reimburs['mianji'] == 3 && empty($mianji)) {
            //                 $mianji = $mianji . $fg . '60-79m²';
            //             }
            //             if (!empty($reimburs) && $reimburs['mianji'] == 2 && empty($mianji)) {
            //                 $mianji = $mianji . $fg . '80m²及以上';
            //             }
            //             if (!empty($reimburs) && $reimburs['mianji'] == 1 && empty($mianji)) {
            //                 $mianji = $mianji . $fg . '80m²以下';
            //             }
            //             $wk = '';
            //             switch ($bus['weikuan']) {
            //                 case '1':
            //                     $wk = '未回款';
            //                     break;
            //                 case '2':
            //                     $wk = '部分回款';
            //                     break;
            //                 case '3':
            //                     $wk = '全部回款';
            //                     break;
            //                 default:
            //                     $wk = '未知';
            //                     break;
            //             }
            //             if ($bus['weikuanstatus'] == 2) {
            //                 $wk = $wk . '(待审核)';
            //             }
            //             if (empty($weikuan)) {
            //                 $weikuan = $wk;
            //             } else {
            //                 $weikuan = $weikuan . '、' . $wk;
            //             }
            //         }
            //     }
            //     $chidao = 0;
            //     $zaotui = 0;
            //     $queka = 0;
            //     $weigui = 0;
            //     $kuanggong = 0;
            //     if (!empty($sign) && $sign['orderid'] != -1) {
            //         if ($sign['monstar'] <= 1 || $sign['aftstar'] <= 1) {
            //             $queka += 1;
            //         }
            //         if ($sign['monstar'] == 3) {
            //             $chidao += 1;
            //         }
            //         if ($sign['aftstar'] == 3) {
            //             $zaotui += 1;
            //         }
            //         if ($sign['monwei'] == 2) {
            //             $weigui += 1;
            //         }
            //         if ($sign['afterwei'] == 2) {
            //             $weigui += 1;
            //         }
            //     }
            //     if (!empty($sign) && $sign['orderid'] == -1) {
            //         $kuanggong += 1;
            //     }
            //     $dzkhlx = trim($sign['btaddress'] ?? '');
            //     if (empty($dzkhlx)) {
            //         $dzkhlx =  $dzkhlx . trim($sign['btname'] ?? '');
            //     } else {
            //         $dzkhlx = $dzkhlx . '|' . trim($sign['btname'] ?? '');
            //     }
            //     if (empty($dzkhlx)) {
            //         $dzkhlx =  $dzkhlx . trim($sign['texts'] ?? '');
            //     } else {
            //         $dzkhlx =  $dzkhlx . '|' . trim($sign['texts'] ?? '');
            //     }
            //     if ($shang['i'] > 0 && $shang['orderid'] == $sign['orderid']) {
            //         $shang['lianxu'] += 1;
            //         $shang['chidao'] += $chidao;
            //         $shang['zaotui'] += $zaotui;
            //         $shang['queka'] += $queka;
            //         $shang['weigui'] += $weigui;
            //         $shang['kuanggong'] += $kuanggong;
            //         $data[$shang['key']] = [
            //             'name' => trim($users['account'] ?? ''),
            //             'date' => $shang['frist'] . ' ~ ' . $i,
            //             'groups' => $groups,
            //             'address' => trim($sign['addresstext'] ?? ''),
            //             // 'dzkhlx' => $dzkhlx,
            //             'kehuname' => $kehuname,
            //             'type' => $type,
            //             'days' => (float)$shang['lianxu'],
            //             'weikuan' => trim($weikuan ?? ''),
            //             'areas' => trim($mianji . $xiu),
            //             'dpxx' => $dpxx,
            //             'weigui' => $shang['weigui'],
            //             'chidao' => $shang['chidao'],
            //             'zaotui' => $shang['zaotui'],
            //             'queka' => $shang['queka'],
            //             'kuanggong' => $shang['kuanggong'],
            //         ];
            //     } else {
            //         $shang['orderid'] = $sign['orderid'];
            //         $shang['frist'] = $i;
            //         $shang['lianxu'] = 1;
            //         $shang['chidao'] = $chidao;
            //         $shang['zaotui'] = $zaotui;
            //         $shang['queka'] = $queka;
            //         $shang['weigui'] = $weigui;
            //         $shang['kuanggong'] = $kuanggong;
            //         $data[] = [
            //             'name' => trim($users['account'] ?? ''),
            //             'date' => $i ?? '',
            //             'groups' => $groups,
            //             'address' => trim($sign['addresstext'] ?? ''),
            //             // 'dzkhlx' => $dzkhlx,
            //             'kehuname' => $kehuname,
            //             'type' => $type,
            //             'days' => (float)$shang['lianxu'],
            //             'weikuan' => trim($weikuan ?? ''),
            //             'areas' => trim($mianji . $xiu),
            //             'dpxx' => $dpxx,
            //             'weigui' => $shang['weigui'],
            //             'chidao' => $shang['chidao'],
            //             'zaotui' => $shang['zaotui'],
            //             'queka' => $shang['queka'],
            //             'kuanggong' => $shang['kuanggong'],
            //         ];
            //         $shang['key'] = count($data) - 1;
            //     }
            //     $shang['i'] = $i;
            // }
        }
        exportDataToExcel($title, $data, $dudao_text . date('Y年m月', $time) . '打卡', true, false, $conditions, $merge_cells);
    }



    public function uploadtk_status()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $reimburs = (new Uploadtk())->where(['id' => $data['id'], 'status' => 1])->find();
            if (empty($reimburs)) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单不存在或处于不可审核状态']);
            }
            $adminid = request()->admin['id'] ?? 0;
            switch ($data['status']) {
                case '2':
                    $res = (new Uploadtk())->where(['id' => $data['id'], 'status' => 1])->update(['status' => $data['status'], 'adminid' => $adminid]);
                    if ($res) {
                        (new Users())->where('id', $$reimburs['user_id'])->update(['hjtz' => 0]);
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                case '3':
                    $res = (new Uploadtk())->where(['id' => $data['id'], 'status' => 1])->update(['status' => $data['status'], 'adminid' => $adminid]);
                    if ($res) {
                        (new Users())->where('id', $reimburs['user_id'])->update(['hjtz' => 0]);
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'data' => [], 'msg' => '状态错误']);
                    break;
            }
            return json(['status' => 1, 'data' => [], 'msg' => '操作失败']);
        }
    }

    public function shop_reimburs()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $reimburs = (new Reimburs())->where(['orderid' => $data['id'], 'type' => $data['status'], 'old' => 1])->count();
            if ($reimburs <= 0) {
                return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
            }
            $res = (new Reimburs())->where(['orderid' => $data['id'], 'type' => $data['status']])->update(['old' => 2]);
            if ($res) {
                return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['status' => 1, 'data' => [], 'msg' => '操作失败']);
        }
    }

    public function weikuan_status()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $admin = $this->request->admin;
            $groups = explode(',', $this->request->admin['groups']) ?? [];
            if ($admin['type'] == 3) {
                $business = (new Business())->where(['id' => $data['id']])->where(['type' => $groups])->find();
            } else {
                $business = (new Business())->where(['id' => $data['id']])->where(['type' => $groups])->find();
            }
            if (empty($business)) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单不存在或无权限']);
            }
            if ($business['weikuan'] >= 3) {
                return json(['status' => 1, 'data' => [], 'msg' => '尾款已确认，无需修改']);
            }
            if ($business['weikuan'] == $data['status']) {
                return json(['status' => 1, 'data' => [], 'msg' => '状态未变更，无需操作']);
            }
            $post = [];
            $post['weikuan'] = $data['status'];
            $post['weikuancw'] = $data['status'];
            $res = (new Business())->where(['id' => $data['id']])->update($post);
            if ($res) {
                return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['status' => 1, 'data' => [], 'msg' => '操作失败']);
        }
    }

    public function store_status()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $reimburs = (new Business())->where(['id' => $data['id']])->find();
            if (empty($reimburs)) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单不存在']);
            }
            $message = [];
            $post = [];
            $post['isshenhe'] = $data['status'];
            switch ($data['status']) {
                case '1':
                    if ($reimburs['schedule'] == 2) {
                        if ($reimburs['foundation'] == 1) {
                            $post['schedule'] = 3;
                            $post['status'] = 2;
                        }
                        if ($reimburs['foundation'] == 2 && $reimburs['contract'] == 2) {
                            $post['schedule'] = 3;
                            $post['status'] = 2;
                            $message[] = [
                                'orderid' => $reimburs['id'],
                                'user_id' =>  $reimburs['suid'],
                                'ouser_id' => 0,
                                'status' => $reimburs['schedule'],
                                'endstatus' => $reimburs['schedule'],
                                'text' => '您的售后单选址完成，请填写信息',
                            ];
                        }
                        $message[] = [
                            'orderid' => $reimburs['id'],
                            'user_id' =>  $reimburs['duid'],
                            'ouser_id' => 0,
                            'status' => $reimburs['schedule'],
                            'endstatus' => $reimburs['schedule'],
                            'text' => '选址审核通过，可前往补充合同或查看状态',
                        ];
                    } else {
                        $message[] = [
                            'orderid' => $reimburs['id'],
                            'user_id' =>  $reimburs['duid'],
                            'ouser_id' => 0,
                            'status' => $reimburs['schedule'],
                            'endstatus' => $reimburs['schedule'],
                            'text' => '选址信息审核通过，可前往补充合同信息或查看状态',
                        ];
                    }
                    $res = (new Business())->where(['id' => $data['id']])->update($post);
                    if ($res) {
                        if (count($message) > 0) {
                            (new Messages())->allowfield(true)->saveAll($message);
                        }
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                case '3':
                    $message[] = [
                        'orderid' => $reimburs['id'],
                        'user_id' =>  $reimburs['duid'],
                        'ouser_id' => 0,
                        'status' => $reimburs['schedule'],
                        'endstatus' => $reimburs['schedule'],
                        'text' => '您的选址信息审核驳回，请联系管理员',
                    ];
                    $res = (new Business())->where(['id' => $data['id']])->update($post);
                    if ($res) {
                        if (count($message) > 0) {
                            (new Messages())->allowfield(true)->saveAll($message);
                        }
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'data' => [], 'msg' => '状态错误']);
                    break;
            }
            return json(['status' => 1, 'data' => [], 'msg' => '操作失败']);
        }
    }

    public function weikuans_status()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $reimburs = (new Business())->where(['id' => $data['id']])->find();
            if (empty($reimburs)) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单不存在']);
            }
            $post = [];
            $post['isshenhe'] = $data['status'];
            switch ($data['status']) {
                case '1':
                    $post['weikuanstatus'] = 1;
                    $res = (new Business())->where(['id' => $data['id']])->update($post);
                    if ($res) {
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                case '3':
                    $post['weikuanstatus'] = 1;
                    $post['weikuan'] = $reimburs['weikuanback'];
                    $res = (new Business())->where(['id' => $data['id']])->update($post);
                    if ($res) {
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'data' => [], 'msg' => '状态错误']);
                    break;
            }
            return json(['status' => 1, 'data' => [], 'msg' => '操作失败']);
        }
    }

    public function dingjin_status()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $reimburs = (new Business())->where(['id' => $data['id']])->find();
            if (empty($reimburs)) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单不存在']);
            }
            $post = [];
            $post['qkqueren'] = $data['status'];
            switch ($data['status']) {
                case '2':
                    $res = (new Business())->where(['id' => $data['id']])->update($post);
                    if ($res) {
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'data' => [], 'msg' => '状态错误']);
                    break;
            }
            return json(['status' => 1, 'data' => [], 'msg' => '操作失败']);
        }
    }

    public function bi_status()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $reimburs = (new Business())->where(['id' => $data['id']])->find();
            if (empty($reimburs)) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单不存在']);
            }
            if ($data['status'] == 1) {
                $res = (new Business())->where(['id' => $data['id']])->update(['schedule' => 9, 'status' => 5]);
            } elseif ($data['status'] == 2) {
                $res = (new Business())->where(['id' => $data['id']])->update(['bicloses' => 2]);
            } elseif ($data['status'] == 3) {
                $res = (new Business())->where(['id' => $data['id']])->update(['bicloses' => 1]);
            } else {
                return json(['status' => 1, 'data' => [], 'msg' => '状态错误']);
            }
            if ($res) {
                return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['status' => 1, 'data' => [], 'msg' => '操作失败']);
        }
    }

    public function shop_status()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $reimburs = (new Business())->where(['id' => $data['id']])->find();
            if (empty($reimburs)) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单不存在']);
            }
            switch ($data['status']) {
                case '1':
                    $res = (new Business())->where(['id' => $data['id']])->update(['luru' => $data['status']]);
                    if ($res) {
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                case '2':
                    $res = (new Business())->where(['id' => $data['id']])->update(['luru' => $data['status']]);
                    if ($res) {
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'data' => [], 'msg' => '状态错误']);
                    break;
            }
            return json(['status' => 1, 'data' => [], 'msg' => '操作失败']);
        }
    }

    public function vip_status()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $reimburs = (new Business())->where(['id' => $data['id']])->find();
            if (empty($reimburs)) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单不存在']);
            }
            switch ($data['status']) {
                case '1':
                    $data['value'] = '';
                    $res = (new Business())->where(['id' => $data['id']])->update(['svip' => $data['status'], 'viptext' => $data['value']]);
                    if ($res) {
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                case '2':
                    if (empty($data['value'])) {
                        return json(['status' => 1, 'data' => [], 'msg' => '请填写标注语']);
                    }
                    $res = (new Business())->where(['id' => $data['id']])->update(['svip' => $data['status'], 'viptext' => $data['value']]);
                    if ($res) {
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'data' => [], 'msg' => '状态错误']);
                    break;
            }
            return json(['status' => 1, 'data' => [], 'msg' => '操作失败']);
        }
    }

    public function reimburs_status()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $reimburs = (new Reimburs())->where(['id' => $data['id'], 'status' => [1, 2]])->find();
            if (empty($reimburs)) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单不存在或处于不可审核状态']);
            }
            $adminid = request()->admin['id'] ?? 0;
            switch ($data['status']) {
                case '2':
                    $data['value'] = $data['value'] ?? '';
                    $groups = $reimburs['groups'];
                    if (!empty($data['groups'])) {
                        $groups = $data['groups'];
                    }
                    $res = (new Reimburs())->where(['id' => $data['id'], 'status' => 1])->update(['status' => $data['status'], 'text' => $data['value'], 'adminid' => $adminid, 'groups' => $groups]);
                    if ($res) {
                        (new Message())->allowfield(true)->save([
                            'type' => 2,
                            'orderid' => $data['id'],
                            'user_id' =>  $reimburs['user_id'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 0,
                            'text' => '报销(预支)申请审核通过，请等待打款!',
                            'yue' => 2
                        ]);
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功,为避免遗忘，请打款后再确认我已打款']);
                    }
                    break;
                case '3':
                    if (empty($data['value'])) {
                        return json(['status' => 1, 'data' => [], 'msg' => '请填写驳回理由']);
                    }
                    $res = (new Reimburs())->where(['id' => $data['id'], 'status' => 1])->update(['status' => $data['status'], 'text' => $data['value'], 'adminid' => $adminid]);
                    if ($res) {
                        (new Message())->allowfield(true)->save([
                            'type' => 2,
                            'orderid' => $data['id'],
                            'user_id' =>  $reimburs['user_id'],
                            'ouser_id' => 0,
                            'status' => 2,
                            'endstatus' => 0,
                            'text' => '报销(预支)申请被驳回!',
                            'yue' => 2
                        ]);
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                case '8':
                    if ($reimburs['status'] != 2) {
                        return json(['status' => 1, 'data' => [], 'msg' => '该订单未审核通过无法撤销重审']);
                    }
                    $res = (new Reimburs())->where(['id' => $data['id'], 'status' => 2])->update(['dk' => 1, 'status' => 1]);
                    if ($res) {
                        (new Message())->allowfield(true)->save([
                            'type' => 2,
                            'orderid' => $data['id'],
                            'user_id' =>  $reimburs['user_id'],
                            'ouser_id' => 0,
                            'status' => 3,
                            'endstatus' => 0,
                            'text' => '报销(预支)申请被撤回重新审核!',
                            'yue' => 2
                        ]);
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                case '9':
                    if ($reimburs['status'] != 2) {
                        return json(['status' => 1, 'data' => [], 'msg' => '该订单未审核通过无法确认打款']);
                    }
                    $res = (new Reimburs())->where(['id' => $data['id'], 'status' => 2])->update(['dk' => 2]);
                    if ($res) {
                        (new Message())->allowfield(true)->save([
                            'type' => 2,
                            'orderid' => $data['id'],
                            'user_id' =>  $reimburs['user_id'],
                            'ouser_id' => 0,
                            'status' => 4,
                            'endstatus' => 0,
                            'text' => '报销被标记已打款!',
                            'yue' => 2
                        ]);
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                case '100':
                    if ($reimburs['tongyi'] != 1) {
                        return json(['status' => 1, 'data' => [], 'msg' => '非可同意状态']);
                    }
                    $res = (new Reimburs())->where(['id' => $data['id'], 'tongyi' => 1])->update(['tongyi' => 2]);
                    if ($res) {
                        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'data' => [], 'msg' => '状态错误']);
                    break;
            }
            return json(['status' => 1, 'data' => [], 'msg' => '操作失败']);
        }
    }

    public function Reimburs()
    {
        $model = new Reimburs();
        $data = $this->request->get();
        $results = $model->alias('rs')->field('rs.*')->leftjoin('user u', 'rs.user_id = u.id')->leftjoin('business b', 'rs.orderid = b.id')->order('rs.id desc');
        if (!empty($data['timess2'])) {
            $rbsid = (new ReimbursLog())->where('cfdates', 'like', '%' . trim($data['timess2']))->column('reimbursid');
            if (count($rbsid) > 0) {
                $results = $results->where(['rs.id' => $rbsid]);
            } else {
                $results = $results->where(['rs.id' => 0]);
            }
        }
        if (!empty($data['title'])) {
            $results = $results->where('rs.name|rs.address|rs.text|b.areas|b.title|b.phone|b.address|b.phone|b.mobile|b.phone2|b.name2|b.getaddress|b.name|b.province|b.city|b.area', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['timess'])) {
            $results = $results->whereBetweenTime('rs.created', $data['timess']);
        }
        if (!empty($data['type'])) {
            $results = $results->where('rs.type', $data['type']);
        }
        if (!empty($data['xmtype'])) {
            $results = $results->where('rs.groups|b.type', $data['xmtype']);
        }
        $admin = $this->request->admin;
        $groups = explode(',', $this->request->admin['groups']) ?? [];
        if ($admin['type'] == 3 || $admin['type'] == 4) {
            $results = $results->where(['rs.groups|b.type' => $groups]);
        }
        if ($admin['type'] == 4) {
            $results = $results->where(['u.bx' => $admin['id']]);
        } else {
            $results = $results->where(['u.bx' => 0]);
        }
        if (!empty($data['status'])) {
            $results = $results->where('rs.status', $data['status']);
        } elseif ($admin['type'] == 2) {
            //$results = $results->where('rs.status', 2);
        }
        if (!empty($data['ordertype'])) {
            $results = $results->where('rs.jobtype|b.ordertype', $data['ordertype']);
        }
        if (!empty($data['dk'])) {
            $results = $results->where('rs.dk', $data['dk'])->where('rs.status', 2);
        }
        if (!empty($data['reimburs_type'])) {
            $colun = (new ReimbursLog())->where('type', $data['reimburs_type'])->column('id');
            $results = $results->where(['rs.id' => $colun]);
        }
        if (!empty($data['uuuid'])) {
            $results = $results->where('rs.user_id', $data['uuuid']);
        }
        if (request()->admin['type'] != 1 && request()->admin['type'] != 2 && request()->admin['type'] != 4) {
            $results = $results->where(['rs.status' => [2, 3]]);
        }
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            $result['typename'] = '';
            if ($result['type'] == 1) {
                $result['typename'] = '选址';
            }
            if ($result['type'] == 2) {
                $result['typename'] = '开业';
            }
            if ($result['type'] == 99) {
                $result['typename'] = '日常报销';
            }
            if ($result['type'] == 100) {
                $result['typename'] = '费用预支';
            }
            $business = (new Business())->where('id', $result['orderid'])->find() ?? '';
            //任务单状态返回
            $schedule = (new Business())->where('id', $result['orderid'])->value('schedule') ?? 0;
            $adminuser = (new Admin())->where('id', $result['adminid'])->value('nickname') ?? '';
            $result['baoxiaosons'] = $business['baoxiaosons'] ?? 0;
            $result['schedule_text'] = config()["config"]['schedule_nav'][$schedule] ?? '';
            $result['schedule_text2'] = config()["config"]['schedule_text'][$schedule] ?? '';
            $result['user_name'] = (new Users())->where('id', $result['user_id'])->value('account') ?? '用户已删除';
            $result['status_text'] = config()["config"]['reimburs_status'][$result['status']] ?? '';
            $result['status_text'] = config()["config"]['reimburs_status'][$result['status']] ?? '';
            // if ((request()->admin['type'] == 1 || request()->admin['type'] == 2) && $result['baoxiaosons'] == 2 && $result['tongyi'] == 2) {
            //     $result['status_text'] = '已同意';
            // }
            if (empty($business)) {
                $result['groupname'] = config()["config"]['typeo'][$result['groups']] ?? '';
            } else {
                $result['groupname'] = config()["config"]['typeo'][$business['type']] ?? '';
            }
            $result['jobtypename'] = config()["config"]['ordertype'][$result['jobtype']] ?? '';
            $result['hktype_text'] = config()["config"]['hktype_text'][$result['hktype']] ?? '未填写';
            $result['name'] = $business['name'] ?? '';
            $result['phone'] = $business['phone'] ?? '';
            $logs = (new ReimbursLog())->where('reimbursid', $result['id'])->select();
            foreach ($logs as $log) {
                $log['pinzheng'] = json_decode($log['pinzheng'] ?? '', true) ?? [];
                $log['fujian'] = json_decode($log['fujian'] ?? '', true) ?? [];
                $log['typename'] = config()["config"]['reimburs_type'][$log['type']] ?? '';
                $log['mingxi'] = json_decode($log['mingxi'] ?? '', true) ?? [];
                if ($log['isnew'] == 2) {
                    if (!empty($log['cfdates'])) {
                        $log['remark'] = $log['cfdates'] . ' ~ ' . $log['dddates'] . '  ' . $log['cfaddress'] . '至' . $log['ddaddress'] . $log['kehuname'] . $log['gztype_name'];
                    }
                    foreach ($log['mingxi'] as $mingxi) {
                        $log['remark'] = $log['remark'] . '
' . ($mingxi['title'] ?? '') . '(' . ($mingxi['total'] ?? 0) . '元)';
                    }
                }
            }
            $result['log'] = $logs;
            $result['peoples'] = $adminuser;
            //查询督导上月合同邮寄单
            $result['htshenghe'] = 0;
            $qishu = date('Ym', strtotime('-1 month'));
            $uporder = (new Uploadtk())->where(['user_id' => $result['user_id'], 'qishu' => $qishu])->find();
            if (!empty($uporder)) {
                $result['htshenghe'] = $uporder['status'];
            }
            $result['cishu'] = (new Users())->where('id', $result['user_id'])->value('hjtz') ?? 0;
        }
        $types = config()["config"]['type'] ?? [];
        $ordertype = config()["config"]['ordertype'] ?? [];
        return view(null, [
            'types' => $types,
            'typeslist' => json_encode($types),
            'ordertype' => $ordertype,
            'list' => $results,
            'uuulist' => (new Users())->where(['del' => 1, 'type' => 2])->select(),
            'reimburs_type' => config()["config"]['reimburs_type'] ?? [],
            'reimburs_status' => config()["config"]['reimburs_status'] ?? [],
            'adminid' => request()->admin['id'],
            'admintype' => request()->admin['type']
        ]);
    }

    public function sendmessage()
    {
        $data = $this->request->post();
        if (empty($data['id']) || empty($data['value']) || empty($data['uid'])) {
            return json(['status' => 1, 'msg' => '参数信息错误']);
        }
        $openid = (new Users())->where('id', $data['uid'])->value('openid');
        if (empty($openid)) {
            return json(['status' => 1, 'msg' => '该人员未授权消息提醒,请线下联系']);
        }
        $order = (new Business())->where('id', $data['id'])->find();
        if (empty($order)) {
            return json(['status' => 1, 'msg' => '未关联订单']);
        }
        $res = (new Message())->allowfield(true)->save([
            'orderid' => $data['id'],
            'user_id' =>  $data['uid'],
            'ouser_id' => 0,
            'status' => $order['schedule'],
            'endstatus' => $order['schedule'],
            'text' => $data['value'],
            'yue' => 2
        ]);
        if ($res) {
            return json(['status' => 0, 'msg' => '操作成功']);
        }
        return json(['status' => 1, 'msg' => '操作失败，请重试']);
    }

    public function hetong_message()
    {
        $data = $this->request->post();
        $res = (new Message())->allowfield(true)->save([
            'type' => 2,
            'orderid' => $data['id'],
            'user_id' =>  $data['status'],
            'ouser_id' => 0,
            'status' => 4,
            'endstatus' => 0,
            'text' => '请尽快邮寄上月合同/回执单!',
            'yue' => 2
        ]);
        if ($res) {
            (new Users())->where('id', $data['status'])->setInc('hjtz', 1);
            return json(['status' => 0, 'msg' => '操作成功']);
        }
        return json(['status' => 1, 'msg' => '操作失败，请重试']);
    }
    public function message()
    {
        $type = $this->request->admin['type'];
        $where = [];
        $where[] = ['type', '=', 1];
        if ($type == 1) {
            $where[] = ['status', '=', 1];
        } elseif ($type == 2) {
            $where[] = ['status', '=', 5];
        } else {
            $where[] = ['status', '=', -1];
        }
        $list = (new Message())->where($where)->group('created')->order('id desc');
        $list = $list;
        $list = $list->paginate(15);
        foreach ($list as $result) {
            $result['schedule_text'] = config()["config"]['schedule_nav'][$result['status']] ?? '';
            $result['schedule_text2'] = config()["config"]['schedule_text'][$result['status']] ?? '';
            $result['eschedule_text'] = config()["config"]['schedule_nav'][$result['endstatus']] ?? '';
            $result['eschedule_text2'] = config()["config"]['schedule_text'][$result['endstatus']] ?? '';
        }
        return view(null, [
            'list' => $list
        ]);
    }

    public function ajaxmessage()
    {
        $type = $this->request->admin['type'];
        $where = [];
        $where[] = ['type', '=', 1];
        if ($type == 1) {
            $where[] = ['status', '=', 1];
        } elseif ($type == 2) {
            $where[] = ['status', '=', 5];
        } else {
            $where[] = ['status', '=', -1];
        }
        $count = (new Message())->group('created')->order('created desc')->where($where)->where('yue', 1)->value('id') ?? 0;
        $rdsname = 'messageget' . request()->admin['id'] . 'ids' . $count;
        $messageget = Redis::get($rdsname);
        if ($messageget) {
            return json(['count' => 0, 'dingjincount' => 0, 'shenhecount' => 0, 'msg' => '获取成功']);
        }
        Redis::setex($rdsname, 10, 10);
        $shenhe = (new Business())->where(['isshenhe' => 2, 'schedule' => [1, 2, 3]])->count();
        $dingjincount = (new Business())->where(['qktype' => 1, 'qkqueren' => 1, 'status' => [1, 2, 3, 5]])->count();
        return json(['count' => $count, 'shenhecount' => $shenhe, 'dingjincount' => $dingjincount, 'msg' => '获取成功']);
    }


    public function message_status()
    {
        if ($this->request->isPost()) {
            $type = $this->request->admin['type'];
            $where = [];
            $where[] = ['type', '=', 1];
            if ($type == 1) {
                $where[] = ['status', '=', 1];
            } elseif ($type == 2) {
                $where[] = ['status', '=', 5];
            } else {
                $where[] = ['status', '=', -1];
            }
            Db::startTrans();
            try {
                (new Message())->where($where)->where('yue', 1)->update(['yue' => 2]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'msg' => $e->getMessage()]);
            }
            return json(['status' => 0, 'msg' => '操作成功']);
        }
    }

    public function riderlat()
    {
        $id = $this->request->get('id/d', 0);
        $dates = $this->request->get('title') ?? date('Y-m-d');
        $startime = strtotime($dates);
        $end =  strtotime($dates) + 86400;
        $getlats = Redis::zRangeByScore('getlatlonarrs' . $id, $startime, $end);
        $miaoshu = [];
        $lists = array_unique($getlats);
        foreach ($lists as $k => &$getlat) {
            $time = Redis::zScore('getlatlonarrs' . $id, $getlat) ?? 0;
            $url = 'https://restapi.amap.com/v3/geocode/regeo';
            $text = '未知地址';
            $res = api_curl($url, ['location' => $getlat, 'key' => 'c400abfe779387dc8ded64d7db8dbbac', 'extensions' => 'base']);
            if (!empty($res['regeocode']['formatted_address'])) {
                $text = $res['regeocode']['formatted_address'];
            }
            $miaoshu[] = [
                'text' => $text,
                'time' => date('Y-m-d H:i:s', $time)
            ];
            $getlat = explode(',', $getlat);
            if (count($getlat) < 2 || $getlat[0] == 'undefined') {
                unset($lists[$k]);
            }
        }
        $lists = array_values($lists);
        return view('', ['getlats' => $lists, 'miaoshu' => $miaoshu]);
    }

    public function import_batch_send()
    {
        $imageFilePath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/xlsimgs/'; //图片本地存储的路径
        if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
            mkdir($imageFilePath, 777, true);
        }
        try {
            //上传excel文件
            $file = request()->file('file');
            $file_size = $_FILES['file']['size'];
            if ($file_size > 10 * 1024 * 1024) {
                $this->error('文件大小不能超过10M');
                exit();
            }
            //将文件保存到public/uploads目录下面
            $info = $file->validate(['ext' => 'xls,xlsx'])->move('./uploads');
            if ($info) {
                //获取上传到后台的文件名
                $fileName = $info->getSaveName();
                //获取文件路径
                $filePath = $_SERVER['DOCUMENT_ROOT'] . '/uploads' . DIRECTORY_SEPARATOR . $fileName;
            } else {
                return json(['status' => '1', 'mag' => '文件过大或格式不正确导致上传失败-_-!']);
            }
            $objRead = IOFactory::createReader('Xls');
            $objRead->setReadDataOnly(true);
            $objSpreadsheet = $objRead->load($filePath);
            $objWorksheet = $objSpreadsheet->getSheet(0);
            $data = $objWorksheet->toArray();
        } catch (\Exception $e) {
            throw $e;
        }
        $error = [];
        if (count($data) > 1) {
            unset($data[0]);
            foreach ($data as $k => $goods) {
                if (mb_strlen($goods[9]) <= 0) {
                    continue;
                }
                $save = [];
                $url = 'https://apis.map.qq.com/ws/place/v1/suggestion';
                $result = api_curl($url, ['keyword' => $goods[9] ?? '', 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D']);
                if (empty($result['data']) || count($result['data']) <= 0) {
                    $length = mb_strlen($goods[9]);
                    for ($i = 1; $i < $length - 1; $i++) {
                        $goods[9] = mb_substr($goods[9], 0, $length - $i);
                        if (mb_strlen($goods[9]) <= 0) {
                            continue;
                        }
                        $result = api_curl($url, ['keyword' => $goods[9] ?? '', 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D']);
                        if (!empty($result['data']) && count($result['data']) > 0) {
                            break;
                        }
                    }
                }
                $url = 'https://apis.map.qq.com/ws/geocoder/v1';
                $results = api_curl($url, ['location' => $result['data'][0]['location']['lat'] . ',' . $result['data'][0]['location']['lng'], 'key' => '2AEBZ-YK23W-XISR6-ROOGV-VOLI7-46FFT', 'poi_options' => 'radius=50;policy=5']);
                $save['lat'] = $result['data'][0]['location']['lat'] ?? 0;
                $save['lon'] = $result['data'][0]['location']['lng'] ?? 0;
                $save['address'] = $results['result']['address'] ?? '';
                $save['getaddress'] = $results['result']['formatted_addresses']['recommend'] ?? '';
                $save['province'] = $results['result']['ad_info']['province'] ?? '';
                $save['city'] = $results['result']['ad_info']['city'] ?? '';
                $save['area'] = $results['result']['ad_info']['district'] ?? '';
                $save['type'] = 1;
                $save['name'] = $goods[4];
                $save['title'] = config()["config"]['type'][$save['type']] ?? '';
                $title = $results['result']['address_reference']['town']['title'] ?? "";
                $save['title'] = $save['title'] . '【' . $title . '店】';
                //查询店铺在没在
                $shop = (new Business())->where('getaddress', $save['getaddress'])->find();
                if (!empty($shop)) {
                    $error[] = ['key' => $k + 1, 'msg' => '地址已存在店铺，导入跳过'];
                } else {
                    (new Business())->allowfield(true)->save($save);
                    Db::startTrans();
                    try {
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $error[] = ['key' => $k + 1, 'msg' => $e->getMessage()];
                        continue;
                    }
                }
            }
        } else {
            return json(['status' => '1', 'msg' => '数据不足，无法导入']);
        }
        return json(['status' => 0, 'data' => $error, 'msg' => '操作成功']);
    }

    public function Opend()
    {
        $model = new Opend();
        $data = $this->request->get();
        $results = $model->order('id desc');
        if (!empty($data['status'])) {
            $results = $results->where('status', $data['status']);
        }
        if (!empty($data['czstatus'])) {
            $results = $results->where('czstatus', $data['czstatus']);
        }
        if (!empty($data['businessid'])) {
            $results = $results->where('businessid', $data['businessid']);
        }
        if (!empty($data['user_id'])) {
            $results = $results->where('user_id', $data['user_id']);
        }
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            $result['user'] = (new Users())->where('id', $result['user_id'])->find();
            $result['shop'] = (new Business())->where('id', $result['businessid'])->find();
        }
        $business = (new Business())->where(['status' => [1, 2, 3]])->select();
        $user = (new Users())->select();
        return view(null, [
            'list' => $results,
            'user' => $user,
            'business' => $business
        ]);
    }


    public function opendstr()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data['id']) || empty($data['status'])) {
                return json(['status' => 1, 'msg' => '参数信息错误']);
            }
            if ($data['status'] != 2 && $data['status'] != 3) {
                return json(['status' => 1, 'msg' => '参数信息错误']);
            }
            $opend = (new Opend())->where('id', $data['id'])->find();
            if (empty($opend)) {
                return json(['status' => 1, 'msg' => '审核信息不存在，请重试或刷新页面']);
            }
            if ($opend['czstatus'] != 1) {
                return json(['status' => 1, 'msg' => '信息已审核']);
            }
            if ($data['status'] == 2) {
                $business = (new Business())->where(['status' => [1, 2, 3], 'id' => $opend['businessid']])->find();
                if (empty($business)) {
                    return json(['status' => 1, 'msg' => '店铺信息不存在，请选择取消']);
                }
            }
            Db::startTrans();
            try {
                if ($data['status'] == 2) {
                    (new Business())->where('id', $business['id'])->update(['status' => $opend['status'], 'mobile' => $opend['mobile'], 'times' => $opend['times']]);
                }
                (new Opend())->where('id', $data['id'])->update(['czstatus' => $data['status']]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'msg' => $e->getMessage()]);
            }
            return json(['status' => 0, 'msg' => '操作成功']);
        }
    }

    public function shoplist()
    {
        $model = new Business();
        $data = $this->request->get();
        $results = $model->order(['updated' => 'desc', 'istop' => 'desc', 'created' => 'desc']);
        if (!empty($data['id'])) {
            $data['id'] = explode(',', $data['id']);
            $results = $results->where(['id' => $data['id']]);
        }
        if (!empty($data['title'])) {
            $results = $results->where('areas|title|address|htqdr|phone|mobile|phone2|name2|getaddress|name|province|city|area', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['old'])) {
            $results = $results->where('old', $data['old']);
        }
        if (!empty($data['svip'])) {
            if ($data['svip'] == 1) {
                $results = $results->where(['svip' => [0, 1]]);
            } else {
                $results = $results->where(['svip' => [2]]);
            }
        }
        if (!empty($data['hetongtype'])) {
            if ($data['hetongtype'] >= 4) {
                $results = $results->where('hetongtype', 0);
            } else {
                $results = $results->where('hetongtype', $data['hetongtype']);
            }
        }
        if (!empty($data['isshen'])) {
            $results = $results->where('isshenhe', $data['isshen']);
        }
        if (!empty($data['weikuanstatus'])) {
            $results = $results->where('weikuanstatus', $data['weikuanstatus']);
        }
        if (!empty($data['dingjin'])) {
            $results = $results->where('qktype', 1)->where('qkqueren', 1);
        }
        if (!empty($data['xtimes'])) {
            $results = $results->where('xtimes', '');
        }
        if (!empty($data['timestype']) && !empty($data['timess'])) {
            $times = explode('~', $data['timess']);
            if (count($times) >= 2) {
                $start = trim($times[0]) . ' 00:00:00';
                $end = trim($times[1]) . ' 23:59:59';
                $results = $results->whereTime($data['timestype'], 'between', [$start, $end]);
            } else {
                $results = $results->where('id', 0);
            }
        }
        if (!empty($data['schedule'])) {
            $results = $results->where('schedule', $data['schedule']);
        }
        if (!empty($data['type'])) {
            $results = $results->where('type', $data['type']);
        }
        if (!empty($data['ordertype'])) {
            $results = $results->where('ordertype', $data['ordertype']);
        }
        if (!empty($data['oldordertype'])) {
            $results = $results->where('oldordertype', $data['oldordertype']);
        }
        if (!empty($data['isfirst'])) {
            $results = $results->where('isfirst', $data['isfirst'])->where(['old' => [2, 3]]);
        }
        if (!empty($data['ishuo'])) {
            $results = $results->where('ishuo', $data['ishuo'])->where(['old' => [2, 3]]);
        }
        if (!empty($data['weikuan'])) {
            $results = $results->where('weikuan', $data['weikuan'])->where(['old' => [2, 3]]);
        }
        if (!empty($data['zhuangxiu'])) {
            $results = $results->where('zhuangxiu', $data['zhuangxiu'])->where(['old' => [2, 3]]);
        }
        if (!empty($data['shanghuo'])) {
            $results = $results->where('shanghuo', $data['shanghuo'])->where(['old' => [2, 3]]);
        }
        if (!empty($data['huozhuang'])) {
            $results = $results->where('huozhuang', $data['huozhuang'])->where(['old' => [2, 3]]);
        }
        if (!empty($data['yuid'])) {
            $results = $results->where('user_id|yuid', $data['yuid']);
        }
        if (!empty($data['suid'])) {
            $results = $results->where('user_id|suid', $data['suid']);
        }
        if (!empty($data['duid'])) {
            $results = $results->where('user_id|duid|kuid', $data['duid']);
        }
        $admin = $this->request->admin;
        $groups = explode(',', $this->request->admin['groups']) ?? [];
        if ($admin['type'] == 3) {
            $results = $results->where(['type' => $groups]);
        }
        if (!empty($data['xxduid'])) {
            $eeorderid = (new Businessxq())->where(['user_id' => $data['xxduid'], 'type' => 1])->column('orderid') ?? [];
            $results = $results->where(['id' => $eeorderid]);
        }
        if (empty($data['status']) && empty($data['schedule'])) {
            $results = $results->where(['status' => [1, 2, 3, 5]]);
        } elseif (!empty($data['status'])) {
            $results = $results->where(['status' => $data['status']]);
        }
        $limit = 10;
        if (!empty($data['daochu'])) {
            $headArr = ['客户姓名', '客户电话', '区域', '地址', '选址督导', '开业督导', '最新状态'];
            $dataArr = [];
            $limit = 100000;
        }
        $results = $results->paginate($limit, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            if (empty($result['xtimes']) || $result['xtimes'] == '0000-00-00') {
                $result['xtimes'] = '';
            }
            $result['qktype_text'] = config()["config"]['jntype'][$result['qktype']] ?? '';
            $result['ytypes_text'] = config()["config"]['ytypes'][$result['ytypes']] ?? '';
            $result['ytypeslist_text'] = config()["config"]['ytypeslist'][$result['ytypeslist']] ?? '';
            //回款情况说明
            $result['hk_text'] = (new Reimburs())->whereNotNull('hktext')->where('orderid', $result['id'])->value('hktext');
            $result['type'] = config()["config"]['type'][$result['type']] ?? '';
            $result['ordertype_text'] = config()["config"]['ordertype'][$result['ordertype']] ?? '';
            $result['oldordertype_text'] = config()["config"]['ordertype'][$result['oldordertype']] ?? '';
            $result['schedule_text'] = config()["config"]['schedule_nav'][$result['schedule']] ?? '';
            $result['schedule_text2'] = config()["config"]['schedule_text'][$result['schedule']] ?? '';
            $result['user_name'] = '总管理添加';
            $result['images'] = json_decode($result['images'] ?? '', true) ?? [];
            $result['images1'] = json_decode($result['images1'] ?? '', true) ?? [];
            $result['images2'] = json_decode($result['images2'] ?? '', true) ?? [];
            $result['images3'] = json_decode($result['images3'] ?? '', true) ?? [];
            $result['images4'] = json_decode($result['images4'] ?? '', true) ?? [];
            $result['images5'] = json_decode($result['images5'] ?? '', true) ?? [];
            $result['images6'] = json_decode($result['images6'] ?? '', true) ?? [];
            $result['images7'] = json_decode($result['images7'] ?? '', true) ?? [];
            $result['images9'] = json_decode($result['images9'] ?? '', true) ?? [];
            $result['images10'] = json_decode($result['images10'] ?? '', true) ?? [];
            $result['images11'] = json_decode($result['images11'] ?? '', true) ?? [];
            $result['dplist'] = json_decode($result['dplist'] ?? '', true) ?? [];
            $result['sginfo'] = json_decode($result['sginfo'] ?? '', true) ?? [];
            $result['video'] = json_decode($result['video'] ?? '', true) ?? [];
            $result['video1'] = json_decode($result['video1'] ?? '', true) ?? [];
            if ($result['user_id'] > 0) {
                $result['user_name'] = (new Users())->where('id', $result['user_id'])->value('account') ?? '用户已删除';
            }
            $result['shouhuo'] = (new Users())->where('id', $result['suid'])->value('account'); //售后经理
            $result['dudao'] = (new Users())->where('id', $result['duid'])->value('account'); //督导
            $result['yewu'] = (new Users())->where('id', $result['yuid'])->value('account'); //业务经理
            $result['kaiye'] = (new Users())->where('id', $result['kuid'])->value('account'); //督导
            $result['backdata'] = json_decode($result['backdata'] ?? '', true) ?? [];
            $result['xxlist'] = []; //协选人员列表
            //协选人员
            $xxlist = [];
            $xxhave = (new Businessxq())->where(['orderid' => $result['id'], 'type' => 1])->column('user_id') ?? [];
            if (count($xxhave) > 0) {
                foreach ($xxhave as $ks => $xxuser) {
                    $xxusers = (new Users())->where('id', $xxuser)->find();
                    if (!empty($xxusers)) {
                        $xxlist[] = [
                            'id' => $xxusers['id'],
                            'account' => $xxusers['account']
                        ];
                    }
                }
            }
            $result['xxlist'] = $xxlist; //协选人员列表
            $dataArr[] = [
                $result['name'],
                $result['phone'],
                $result['areas'],
                $result['getaddress'] . $result['address'],
                $result['dudao'],
                $result['kaiye'],
                $result['schedule_text']
            ];
        }
        if (!empty($data['daochu'])) {
            excelExport('信息导出', $headArr, $dataArr);
        }
        $types = config()["config"]['type'] ?? [];
        $ordertype   = config()["config"]['ordertype'] ?? [];
        return view(null, [
            'admin' => $admin,
            'ordertype' => $ordertype,
            'list' => $results,
            'types' => $types,
            'ylist' => (new Users())->where('type', 1)->select(),
            'dlist' => (new Users())->where('type', 2)->select(),
            'slist' => (new Users())->where('type', 3)->select(),
            'schedule_nav' => config()["config"]['schedule_nav'] ?? [],
            'ordertype' => config()["config"]['ordertype'] ?? []
        ]);
    }

    public function uploadtk()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require',
                'name' => 'require',
                'ordertype' => 'require',
            ], [
                'type.require' => '项目类型不能为空',
                'name.require' => '客户姓名不能为空',
                'ordertype.require' => '订单类型不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
        } else {
            $model = new Uploadtk();
            $user_id = $this->request->get('user_id', 0);
            $qishu = date('Ym', strtotime('-1 month'));
            $row = $model->where(['user_id' => $user_id, 'qishu' => $qishu])->find();
            if ($row) {
                $row['images'] = json_decode($row['images'] ?? '', true) ?? [];
                $row['names'] = json_decode($row['names'], true) ?? [];
            }
            return view('', [
                'row' => $row,
            ]);
        }
    }


    public function shoplist_back()
    {
        $model = new Business();
        $id = $this->request->get('id/d', 0);
        $row = $model->where('id', $id)->value('backdata') ?? '';
        $row = json_decode($row, true) ?? [];
        $row['images'] = json_decode($row['images'] ?? '', true) ?? [];
        $row['images1'] = json_decode($row['images1'] ?? '', true) ?? [];
        $row['images2'] = json_decode($row['images2'] ?? '', true) ?? [];
        $row['images3'] = json_decode($row['images3'] ?? '', true) ?? [];
        $row['images4'] = json_decode($row['images4'] ?? '', true) ?? [];
        $row['images6'] = json_decode($row['images6'] ?? '', true) ?? [];
        $row['images7'] = json_decode($row['images7'] ?? '', true) ?? [];
        $row['images9'] = json_decode($row['images9'] ?? '', true) ?? [];
        $row['images10'] = json_decode($row['images10'] ?? '', true) ?? [];
        $row['images11'] = json_decode($row['images11'] ?? '', true) ?? [];
        $row['video'] = json_decode($row['video'] ?? '', true) ?? [];
        $row['video1'] = json_decode($row['video1'] ?? '', true) ?? [];
        $types = config()["config"]['type'] ?? [];
        $yewu = (new Users())->where(['type' => 1, 'del' => 1])->select();
        $dudao = (new Users())->where(['type' => 2, 'del' => 1])->select();
        $shouhou = (new Users())->where(['type' => 3, 'del' => 1])->select();
        return view('', [
            'row' => $row,
            'types' => $types,
            'yewu' => $yewu,
            'dudao' => $dudao,
            'shouhou' => $shouhou,
            'schedule_nav' => config()["config"]['schedule_nav'] ?? [],
            'ordertype' => config()["config"]['ordertype'] ?? []
        ]);
    }

    public function shoplist_edit()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $admin = $this->request->admin;
            if ($admin['type'] >= 3) {
                return json(['status' => 1, 'data' => [], 'msg' => '无操作权限']);
            }
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require',
                'name' => 'require',
            ], [
                'type.require' => '项目类型不能为空',
                'name.require' => '客户姓名不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (empty($data['xtimessetting']) && empty($data['ordertype']) && $data['schedule'] != 8) {
                return json(['code' => 1, 'data' => [], 'msg' => '请设置派单类型']);
            }
            if (empty($data['phone'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '请填写客户手机号']);
            }
            if (empty($data['xtimes'])) {
                $data['xtimes'] = '';
            }
            $data['yuid'] = $data['yuid'] ?? 0;
            $data['duid'] = $data['duid'] ?? 0;
            $data['suid'] = $data['suid'] ?? 0;
            $data['kuid'] = $data['kuid'] ?? 0;
            $message = []; //通知数组
            $userstatus = []; //状态变更
            if (!empty($data['lat']) && !empty($data['lon'])) {
                $url = 'https://apis.map.qq.com/ws/geocoder/v1';
                try {
                    $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                    $data['getaddress'] = $result['result']['formatted_addresses']['recommend'] ?? '';
                    $data['province'] = $result['result']['ad_info']['province'] ?? '';
                    $data['city'] = $result['result']['ad_info']['city'] ?? '';
                    $data['area'] = $result['result']['ad_info']['district'] ?? '';
                } catch (\Exception $e) {
                    return json(['code' => 1, 'data' => [], 'msg' =>  $e->getMessage()]);
                }
            }
            if (empty($data['status']) && empty($data['schedule'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '必须选择状态']);
            }
            if (!empty($data['status'])) {
                $data['old'] = 3;
                if ($data['status'] == 5) {
                    $data['schedule'] = 9;
                }
                if ($data['status'] == 4) {
                    $data['schedule'] = 8;
                }
                if ($data['status'] == 3) {
                    $data['schedule'] = 2;
                }
                if ($data['status'] == 2) {
                    $data['schedule'] = 5;
                }
                if ($data['status'] == 1) {
                    $data['schedule'] = 6;
                }
            } else if (!empty($data['schedule'])) {
                if ($data['ordertype'] >= 4 && $data['schedule'] < 4) {
                    //return json(['code' => 1, 'data' => [], 'msg' => '当前派单类型状态请先选择【开业派单】状态']);
                }
                if ($data['schedule'] >= 3 && $data['schedule'] <= 7) {
                    if (empty($data['lat']) || empty($data['lon'])) {
                        return json(['code' => 1, 'data' => [], 'msg' => '地图坐标必选']);
                    }
                }
                if (empty($data['old']) || $data['old'] == 1) {
                    $data['old'] = 2;
                }
                if ($data['schedule'] == 1 || $data['schedule'] == 2) {
                    $data['status'] = 3;
                }
                if ($data['schedule'] == 3 || $data['schedule'] == 4 || $data['schedule'] == 5) {
                    $data['status'] = 2;
                }
                if ($data['schedule'] == 6 || $data['schedule'] == 7) {
                    $data['status'] = 1;
                }
                if ($data['schedule'] == 8) {
                    $data['status'] = 4;
                }
                if ($data['schedule'] == 9) {
                    $data['status'] = 5;
                }
                $data['suid'] = $data['suid'] ?? 0;
                if (empty($data['suid'])) {
                    // return json(['code' => 1, 'data' => [], 'msg' => '必须绑定售后经理']);
                }
                if ($data['schedule'] != 9 && $data['schedule'] != 8 && $data['schedule'] >= 2 && empty($data['duid']) && $data['ordertype'] <= 4) {
                    return json(['code' => 1, 'data' => [], 'msg' => '请选择选址督导']);
                }
                if ($data['schedule'] < 2 && !empty($data['duid'])) {
                    return json(['code' => 1, 'data' => [], 'msg' => '已选择选择选择督导，状态不能为初始状态']);
                }
                if ($data['schedule'] != 9 && $data['schedule'] != 8 && $data['schedule'] >= 5 && empty($data['kuid'])) {
                    return json(['code' => 1, 'data' => [], 'msg' => '请选择开业督导']);
                }
                if ($data['schedule'] < 5 && !empty($data['kuid'])) {
                    return json(['code' => 1, 'data' => [], 'msg' => '已选择选择开业督导，状态必须不低于预备开业状态']);
                }
            }
            $data['xxlist'] = $data['xxlist'] ?? [];
            $xxlist = [];
            if (count($data['xxlist']) > 0) {
                if ($data['duid'] <= 0) {
                    return json(['code' => 1, 'data' => [], 'msg' => '请先选择选址督导再选址协选']);
                }
                $data['xxlist'] = array_unique($data['xxlist']);
                foreach ($data['xxlist'] as $xxuser_id) {
                    $xxlist[] = [
                        'type' => 1,
                        'user_id' => $xxuser_id,
                        'orderid' => $data['id']
                    ];
                }
                //查找是否已经是协选，不是就添加通知
                $haves = (new Businessxq())->where(['type' => 1, 'user_id' => $xxuser_id, 'orderid' => $data['id']])->find();
                if (!empty($data['message']) && $data['message'] == 2 && empty($haves)) {
                    $message[] = [
                        'orderid' => $data['id'],
                        'user_id' =>  $xxuser_id,
                        'ouser_id' => 0,
                        'status' => 1,
                        'endstatus' => $data['schedule'],
                        'text' => '您有协住选址任务单，请注意跟进',
                        'yue' => 2
                    ];
                }
            }
            $model = new Business();
            if (!empty($data['id'])) {
                $business = (new Business())->where('id', $data['id'])->find();
                if (empty($business)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '任务不存在']);
                }
                if (!empty($data['duid']) && $business['duid'] != $data['duid']) {
                    $data['xcreated'] =  date('Y-m-d H:i:s');
                }
                if (!empty($data['kuid']) && $business['kuid'] != $data['kuid']) {
                    $data['ycreated'] =  date('Y-m-d H:i:s');
                }
                if (empty($business['backdata'])) {
                    $data['backdata'] =  json_encode(array_merge($business->toArray(), $data) ?? [], true);
                }
                if (empty($data['oldordertype']) && !empty($data['ordertype']) && $data['schedule'] <= 3) {
                    $data['oldordertype'] = $data['ordertype'];
                } elseif (empty($data['oldordertype']) && !empty($business['ordertype'])) {
                    $data['oldordertype'] = $business['ordertype'];
                }
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
                if ($business['duid'] != $data['duid'] && $data['schedule'] != 8) {
                    if ($data['duid'] > 0) {
                        $userstatus[] = [
                            'type' => 2,
                            'user_id' => $data['duid'],
                            'status' => 2,
                            'orderid' =>  $business['id'],
                        ];
                    }
                    if ($business['duid'] > 0) {
                        $userstatus[] = [
                            'type' => 1,
                            'user_id' => $business['duid'],
                            'status' => 2,
                            'orderid' =>  $business['id'],
                        ];
                    }
                }
                if ($business['kuid'] != $data['kuid'] && $data['schedule'] != 8) {
                    if ($data['kuid'] > 0) {
                        $userstatus[] = [
                            'type' => 2,
                            'user_id' => $data['kuid'],
                            'status' => 2,
                            'orderid' =>  $business['id'],
                        ];
                    }
                    if ($business['kuid'] > 0) {
                        $userstatus[] = [
                            'type' => 1,
                            'user_id' => $business['kuid'],
                            'status' => 2,
                            'orderid' =>  $business['id'],
                        ];
                    }
                }
                //增加通知
                if (!empty($data['message']) && $data['message'] == 2) {
                    // if ($business['duid'] != $data['duid']) {
                    $message[] = [
                        'orderid' => $data['id'],
                        'user_id' =>  $data['duid'],
                        'ouser_id' => $business['duid'],
                        'status' => $business['schedule'],
                        'endstatus' => $data['schedule'],
                        'text' => '您有新的选址任务单，请注意跟进',
                        'yue' => 2
                    ];
                    if ($business['duid'] > 0 && $business['duid'] != $data['duid']) {
                        $message[] = [
                            'orderid' => $data['id'],
                            'user_id' =>  $business['duid'],
                            'ouser_id' => 0,
                            'status' => $business['schedule'],
                            'endstatus' => $data['schedule'],
                            'text' => '您的选址任务单被取消，请留意',
                            'yue' => 2
                        ];
                    }
                    // }
                    // if ($business['kuid'] != $data['kuid']) {
                    $message[] = [
                        'orderid' => $data['id'],
                        'user_id' =>  $data['kuid'],
                        'ouser_id' => $business['kuid'],
                        'status' => $business['schedule'],
                        'endstatus' => $data['schedule'],
                        'text' => '您有新的开业任务单，请注意跟进',
                        'yue' => 2
                    ];
                    if ($business['kuid'] > 0 && $business['kuid'] != $data['kuid']) {
                        $message[] = [
                            'orderid' => $data['id'],
                            'user_id' =>  $business['kuid'],
                            'ouser_id' => 0,
                            'status' => $business['schedule'],
                            'endstatus' => $data['schedule'],
                            'text' => '您的开业任务单被取消，请留意',
                            'yue' => 2
                        ];
                    }
                    // }
                }
            } else {
                if (!empty($data['duid'])) {
                    $data['xcreated'] =  date('Y-m-d H:i:s');
                }
                if (!empty($data['kuid'])) {
                    $data['ycreated'] =  date('Y-m-d H:i:s');
                }
                if (empty($business['backdata'])) {
                    $data['backdata'] =  json_encode($data ?? [], true);
                }
                if (!empty($data['ordertype']) && $data['schedule'] <= 3) {
                    $data['oldordertype'] = $data['ordertype'];
                }
                $res = $model->strict(false)->insertGetId($data);
                $data['id'] = $res;
                if ($data['schedule'] != 8) {
                    if ($data['duid'] > 0) {
                        $userstatus[] = [
                            'type' => 2,
                            'user_id' => $data['duid'],
                            'status' => 2,
                            'orderid' =>  $data['id'],
                        ];
                    }
                }
                if ($data['schedule'] != 8) {
                    if ($data['kuid'] > 0) {
                        $userstatus[] = [
                            'type' => 2,
                            'user_id' => $data['kuid'],
                            'status' => 2,
                            'orderid' =>  $data['id'],
                        ];
                    }
                }
                //增加通知
                if (!empty($data['message']) && $data['message'] == 2) {
                    if ($data['duid'] > 0) {
                        $message[] = [
                            'orderid' => $data['id'],
                            'user_id' =>  $data['duid'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => $data['schedule'],
                            'text' => '您有新的选址任务单，请注意跟进',
                            'yue' => 2
                        ];
                    }
                    if ($data['kuid'] > 0) {
                        $message[] = [
                            'orderid' => $data['id'],
                            'user_id' =>  $data['kuid'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => $data['schedule'],
                            'text' => '您有新的开业任务单，请注意跟进',
                            'yue' => 2
                        ];
                    }
                }
            }
            if ($res) {
                (new Businessxq())->where('orderid', $data['id'])->delete();
                if (count($xxlist) > 0) {
                    (new Businessxq())->allowfield(true)->saveAll($xxlist);
                }
                if (count($message) > 0) {
                    (new Messages())->allowfield(true)->saveAll($message);
                }
                if (count($userstatus) > 0) {
                    foreach ($userstatus as $sgetuser) {
                        (new Userstatus())->UserStatus_m($sgetuser['user_id'], $sgetuser['type'], $sgetuser['orderid'], $sgetuser['status']);
                    }
                }
                return json(['code' => 0, 'data' => [], 'msg' => '操作成功,如需通知请手动通知']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Business();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            $types = config()["config"]['type'] ?? [];
            $yewu = (new Users())->where(['type' => 1])->select();
            $dudao = (new Users())->where(['type' => 2])->select();
            $shouhou = (new Users())->where(['type' => 3])->select();
            $sqlist = [];
            // if (!empty($sqlist)) {
            $sqlist = (new Businessxq())->where('orderid', $id)->select();
            // }
            return view('', [
                'row' => $row,
                'types' => $types,
                'yewu' => $yewu,
                'dudao' => $dudao,
                'sqlist' => $sqlist,
                'admintype' => request()->admin['type'],
                'shouhou' => $shouhou,
                'schedule_nav' => config()["config"]['schedule_nav'] ?? [],
                'ordertype' => config()["config"]['ordertype'] ?? [],
                'ytypes' => config()["config"]['ytypes'] ?? [],
                'ytypeslist' => config()["config"]['ytypeslist'] ?? []
            ]);
        }
    }

    public function shoplist_edit2()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '提交频繁,请' . $rdslist . 's后再提交']);
            }
            Redis::setex('clickreturn', 1, 1);
            $admin = $this->request->admin;
            if ($admin['type'] >= 3) {
                return json(['status' => 1, 'data' => [], 'msg' => '无操作权限']);
            }
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require',
                'name' => 'require',
            ], [
                'type.require' => '项目类型不能为空',
                'name.require' => '客户姓名不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (empty($data['xtimessetting']) && empty($data['ordertype']) && $data['schedule'] != 8) {
                return json(['code' => 1, 'data' => [], 'msg' => '请设置派单类型']);
            }
            if (empty($data['phone'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '请填写客户手机号']);
            }
            if (empty($data['xtimes'])) {
                $data['xtimes'] = '';
            }
            $data['yuid'] = $data['yuid'] ?? 0;
            $data['duid'] = $data['duid'] ?? 0;
            $data['suid'] = $data['suid'] ?? 0;
            $data['kuid'] = $data['kuid'] ?? 0;
            $message = []; //通知数组
            $userstatus = []; //状态变更
            if (!empty($data['lat']) && !empty($data['lon'])) {
                $url = 'https://apis.map.qq.com/ws/geocoder/v1';
                try {
                    $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                    $data['getaddress'] = $result['result']['formatted_addresses']['recommend'] ?? '';
                    $data['province'] = $result['result']['ad_info']['province'] ?? '';
                    $data['city'] = $result['result']['ad_info']['city'] ?? '';
                    $data['area'] = $result['result']['ad_info']['district'] ?? '';
                } catch (\Exception $e) {
                    return json(['code' => 1, 'data' => [], 'msg' =>  $e->getMessage()]);
                }
            }
            if (empty($data['status']) && empty($data['schedule'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '必须选择状态']);
            }
            if (!empty($data['status'])) {
                $data['old'] = 3;
                if ($data['status'] == 5) {
                    $data['schedule'] = 9;
                }
                if ($data['status'] == 4) {
                    $data['schedule'] = 8;
                }
                if ($data['status'] == 3) {
                    $data['schedule'] = 2;
                }
                if ($data['status'] == 2) {
                    $data['schedule'] = 5;
                }
                if ($data['status'] == 1) {
                    $data['schedule'] = 6;
                }
            } else if (!empty($data['schedule'])) {
                // if ($data['ordertype'] >= 4 && $data['schedule'] < 4) {
                //     return json(['code' => 1, 'data' => [], 'msg' => '当前派单类型状态请先选择【开业派单】状态']);
                // }
                if ($data['schedule'] >= 3 && $data['schedule'] <= 7) {
                    if (empty($data['lat']) || empty($data['lon'])) {
                        return json(['code' => 1, 'data' => [], 'msg' => '地图坐标必选']);
                    }
                }
                if (empty($data['old']) || $data['old'] == 1) {
                    $data['old'] = 2;
                }
                if ($data['schedule'] == 1 || $data['schedule'] == 2) {
                    $data['status'] = 3;
                }
                if ($data['schedule'] == 3 || $data['schedule'] == 4 || $data['schedule'] == 5) {
                    $data['status'] = 2;
                }
                if ($data['schedule'] == 6 || $data['schedule'] == 7) {
                    $data['status'] = 1;
                }
                if ($data['schedule'] == 8) {
                    $data['status'] = 4;
                }
                if ($data['schedule'] == 9) {
                    $data['status'] = 5;
                }
                $data['suid'] = $data['suid'] ?? 0;
                if (empty($data['suid'])) {
                    // return json(['code' => 1, 'data' => [], 'msg' => '必须绑定售后经理']);
                }
                if ($data['schedule'] != 9 && $data['schedule'] != 8 && $data['schedule'] >= 2 && empty($data['duid']) && $data['ordertype'] <= 4) {
                    return json(['code' => 1, 'data' => [], 'msg' => '请选择选址督导']);
                }
                if ($data['schedule'] < 2 && !empty($data['duid'])) {
                    return json(['code' => 1, 'data' => [], 'msg' => '已选择选择选择督导，状态不能为初始状态']);
                }
                if ($data['schedule'] != 9 && $data['schedule'] != 8 && $data['schedule'] >= 5 && empty($data['kuid'])) {
                    return json(['code' => 1, 'data' => [], 'msg' => '请选择开业督导']);
                }
                if ($data['schedule'] < 5 && !empty($data['kuid'])) {
                    return json(['code' => 1, 'data' => [], 'msg' => '已选择选择开业督导，状态必须不低于预备开业状态']);
                }
            }
            $data['xxlist'] = $data['xxlist'] ?? [];
            $xxlist = [];
            $model = new Business();
            if (empty($data['topid'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '任务单ID不存在']);
            }
            $business = (new Business())->where('id', $data['topid'])->find();
            if (empty($business)) {
                return json(['code' => 1, 'data' => [], 'msg' => '任务不存在']);
            }
            if (!empty($data['duid']) && $business['duid'] != $data['duid']) {
                $data['xcreated'] =  date('Y-m-d H:i:s');
            }
            if (!empty($data['kuid']) && $business['kuid'] != $data['kuid']) {
                $data['ycreated'] =  date('Y-m-d H:i:s');
            }
            $post = array_merge($business->toArray(), $data) ?? [];
            if (!empty($post['id'])) {
                unset($post['id']);
            }
            $data['backdata'] =  json_encode($post, true);
            $res = $model->strict(false)->insertGetId($post);
            $data['id'] = $res;
            if (count($data['xxlist']) > 0) {
                if ($data['duid'] <= 0) {
                    return json(['code' => 1, 'data' => [], 'msg' => '请先选择选址督导再选址协选']);
                }
                $data['xxlist'] = array_unique($data['xxlist']);
                foreach ($data['xxlist'] as $xxuser_id) {
                    $xxlist[] = [
                        'type' => 1,
                        'user_id' => $xxuser_id,
                        'orderid' => $data['id']
                    ];
                }
            }
            if ($data['schedule'] < 3) {
                if ($data['duid'] > 0) {
                    $userstatus[] = [
                        'type' => 2,
                        'user_id' => $data['duid'],
                        'status' => 2,
                        'orderid' =>  $data['id'],
                    ];
                    $message[] = [
                        'orderid' => $data['id'],
                        'user_id' =>  $data['duid'],
                        'ouser_id' => $business['duid'],
                        'status' => $business['schedule'],
                        'endstatus' => $data['schedule'],
                        'text' => '您有新的选址任务单，请注意跟进',
                        'yue' => 2
                    ];
                }
            }
            if ($data['schedule'] == 5) {
                if ($data['kuid'] > 0) {
                    $userstatus[] = [
                        'type' => 2,
                        'user_id' => $data['kuid'],
                        'status' => 2,
                        'orderid' =>  $business['id'],
                    ];
                    $message[] = [
                        'orderid' => $data['id'],
                        'user_id' =>  $data['kuid'],
                        'ouser_id' => $business['kuid'],
                        'status' => $business['schedule'],
                        'endstatus' => $data['schedule'],
                        'text' => '您有新的开业任务单，请注意跟进',
                        'yue' => 2
                    ];
                }
            }
            if ($res) {
                (new Businessxq())->where('orderid', $data['id'])->delete();
                if (count($xxlist) > 0) {
                    (new Businessxq())->allowfield(true)->saveAll($xxlist);
                }
                if (count($message) > 0) {
                    (new Messages())->allowfield(true)->saveAll($message);
                }
                if (count($userstatus) > 0) {
                    foreach ($userstatus as $sgetuser) {
                        (new Userstatus())->UserStatus_m($sgetuser['user_id'], $sgetuser['type'], $sgetuser['orderid'], $sgetuser['status']);
                    }
                }
                return json(['code' => 0, 'data' => [], 'msg' => '操作成功,如需通知请手动通知']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Business();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            $types = config()["config"]['type'] ?? [];
            $yewu = (new Users())->where(['type' => 1])->select();
            $dudao = (new Users())->where(['type' => 2])->select();
            $shouhou = (new Users())->where(['type' => 3])->select();
            $sqlist = (new Businessxq())->where('orderid', $id)->select();
            return view('', [
                'row' => $row,
                'types' => $types,
                'yewu' => $yewu,
                'dudao' => $dudao,
                'sqlist' => $sqlist,
                'admintype' => request()->admin['type'],
                'shouhou' => $shouhou,
                'schedule_nav' => config()["config"]['schedule_nav'] ?? [],
                'ordertype' => config()["config"]['ordertype'] ?? [],
                'ytypes' => config()["config"]['ytypes'] ?? [],
                'ytypeslist' => config()["config"]['ytypeslist'] ?? []
            ]);
        }
    }

    public function recuser()
    {
        if ($this->request->isGet()) {
            $list = (new Users());
            $data = $this->request->get();
            $typearr = config('config.typepeople');
            if (!empty($data['title'])) {
                $list = $list->where('account|remark', 'like', '%' . $data['title'] . '%');
            }
            if (!empty($data['type'])) {
                $list = $list->where('type', $data['type']);
            }
            if (!empty($data['ustatus'])) {
                $list = $list->where('status', $data['ustatus']);
            }
            if (!empty($data['sorts']) && $data['sorts'] == 1) {
                $list = $list->order('status desc');
            } else if (!empty($data['sorts']) && $data['sorts'] == 2) {
                $list = $list->order('status asc');
            } else {
                $list = $list->order('id desc');
            }
            $list = $list->where('del', 2);
            $list = $list->paginate(15, false, ['query' => $this->request->param()]);
            $ids = [];
            foreach ($list as $result) {
                $ids[] = $result['id'];
                $result['type_text'] = $typearr[$result['type']] ?? '无';
                if ($result['groups'] == 0) {
                    $grouplist  = '无';
                } else {
                    $grouplist = '';
                    $groups = explode(',', $result['groups']) ?? [];
                    foreach ($groups as $group) {
                        $grouplist  = $grouplist . (config()["config"]['type'][$group] ?? '');
                    }
                }
                $result['groups_text'] = $grouplist;
                $result['httext'] = 0;
                if ($result['type'] == 2) {
                    $qishu = date('Ym', strtotime('-1 month'));
                    $uporder = (new Uploadtk())->where(['user_id' => $result['id'], 'qishu' => $qishu])->find();
                    if (!empty($uporder)) {
                        $result['httext'] = $uporder['status'];
                    }
                }
                $result['userstatus'] = $result['status'];
                $result['userstatus_address'] = (new Userstatus())->where(['user_id' => $result['id'], 'orderid' => 0, 'type' => 2])->order('id desc')->value('address');
            }
            return view(null, [
                'ids' => implode(',', $ids),
                'list' => $list,
                'typepeople' => config('config.typepeople')
            ]);
        } else {
            $id = $this->request->post('id/d', 0);
            if (empty($id)) {
                return json(['status' => 1, 'msg' => '请选择恢复用户']);
            }
            $banner = (new Users())->where('id', $id)->find();
            if (empty($banner)) {
                return json(['status' => 1, 'msg' => '用户不存在，请重试']);
            }
            $res = (new Users())->where('id', $id)->update(['del' => 1]);
            if ($res) {
                return json(['status' => 0, 'msg' => '操作成功']);
            }
            return json(['status' => 1, 'msg' => '操作失败']);
        }
    }


    public function user()
    {
        $list = (new Users());
        $data = $this->request->get();
        $typearr = config('config.typepeople');
        $typearr[999999999] = '督导专员';
        // $rdslist = Redis::get('updateaddress');
        // if (!$rdslist) {
        //     Db::startTrans();
        //     try {
        //         $updates = (new Users())->where(['type' => 2, 'del' => 1])->select();
        //         foreach ($updates as $update) {
        //             $address = (new Userstatus())->where(['user_id' => $update['id'], 'orderid' => 0, 'type' => 2])->order('id desc')->value('address');
        //             if($update){}
        //             (new Users())->where(['id' => $update['id']])->update(['address' => $address]);
        //         }
        //         Redis::setex('updateaddress', 60, 60);
        //         Db::commit();
        //     } catch (\Exception $e) {
        //         Db::rollback();
        //     }
        // }
        if (!empty($data['title'])) {
            $list = $list->where('account|remark|address', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['type'])) {
            if ($data['type'] == 999999999) {
                $list = $list->where(['type' => 2, 'sonstype' => 2]);
            } elseif ($data['type'] == 2) {
                $list = $list->where(['type' => $data['type'], 'sonstype' => 1]);
            } else {
                $list = $list->where(['type' => $data['type']]);
            }
        }
        if (!empty($data['groups'])) {
            $list = $list->where('find_in_set(' . $data['groups'] . ',groups)');
        }
        if (!empty($data['yuzhi'])) {
            $list = $list->where('yuzhi', $data['yuzhi']);
        }
        if (!empty($data['fangjia'])) {
            $list = $list->where('fangjia', $data['fangjia']);
        }
        if (!empty($data['ustatus'])) {
            $list = $list->where('status', $data['ustatus'])->where('fangjia', 1);
        }
        if (!empty($data['sorts']) && $data['sorts'] == 1) {
            $list = $list->order('status desc');
        } else if (!empty($data['sorts']) && $data['sorts'] == 2) {
            $list = $list->order('status asc');
        } else {
            $list = $list->order('id desc');
        }
        $list = $list->where('del', 1);
        $list = $list->paginate(15, false, ['query' => $this->request->param()]);
        $ids = [];
        foreach ($list as $result) {
            $ids[] = $result['id'];
            $result['type_text'] = $typearr[$result['type']] ?? '无';
            if ($result['groups'] == 0) {
                $grouplist  = '无';
            } else {
                $grouplist = '';
                $groups = explode(',', $result['groups']) ?? [];
                foreach ($groups as $group) {
                    $grouplist  = $grouplist . (config()["config"]['type'][$group] ?? '');
                }
            }
            $result['groups_text'] = $grouplist;
            $result['httext'] = 0;
            if ($result['type'] == 2) {
                $qishu = date('Ym', strtotime('-1 month'));
                $uporder = (new Uploadtk())->where(['user_id' => $result['id'], 'qishu' => $qishu])->find();
                if (!empty($uporder)) {
                    $result['httext'] = $uporder['status'];
                }
            }
            $result['userstatus'] = $result['status'];
            $result['userstatus_address'] = (new Userstatus())->where(['user_id' => $result['id'], 'orderid' => 0, 'type' => 2])->order('id desc')->value('address');
        }
        $grouplist = config()["config"]['type'];
        return view(null, [
            'ids' => implode(',', $ids),
            'list' => $list,
            'grouplist' => $grouplist,
            'typepeople' => $typearr
        ]);
    }

    public function user_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'account' => 'require',
                'remark' => 'require'
            ], [
                'account.require' => '账号不能为空',
                'remark.require' => '备注信息不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            if (isset($data['password']) && empty($data['password'])) {
                unset($data['password']);
            }
            $data['groups'] = !empty($data['groups']) ? $data['groups'] : [0];
            if (count($data['groups']) <= 0) {
                $data['groups'] = 0;
            }
            if ($data['type'] == 3 && count($data['groups']) > 1) {
                //return json(['code' => 1, 'msg' => '售后人员只能绑定一个分组']);
            }
            if (in_array(0, $data['groups'])) {
                $data['groups'] = 0;
            } else {
                $data['groups'] = implode(',', $data['groups']);
            }
            //查找人物是否已有
            $hauser = (new Users())->where(['account' => $data['account'], 'del' => 1])->find();
            if (!empty($hauser) && !empty($data['id']) && $data['id'] != $hauser['id']) {
                return json(['status' => 1, 'msg' => '账号已存在']);
            } else if (!empty($hauser) && empty($data['id'])) {
                return json(['status' => 1, 'msg' => '账号已存在']);
            }
            if (!empty($data['id'])) {
                $res = (new Users())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                if (empty($data['password'])) {
                    return json(['status' => 1, 'msg' => '密码不能为空']);
                }
                $res = (new Users())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 1, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Users())->where('id', $id)->find();
            if ($row) {
                $row['groups'] = explode(',', $row['groups']) ?? [];
            }
            $grouplist = config()["config"]['type'];
            $adminlist = (new Admin())->where('type', 4)->select();
            return view('', [
                'grouplist' => $grouplist,
                'row' => $row,
                'adminlist' => $adminlist
            ]);
        }
    }

    public function user_del()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id/d', 0);
            if (empty($id)) {
                return json(['status' => 1, 'msg' => '请选择删除项目']);
            }
            $banner = (new Users())->where('id', $id)->find();
            if (empty($banner)) {
                return json(['status' => 1, 'msg' => '用户不存在，请重试']);
            }
            $res = (new Users())->where('id', $id)->update(['del' => 2]);
            if ($res) {
                return json(['status' => 0, 'msg' => '操作成功']);
            }
            return json(['status' => 1, 'msg' => '操作失败']);
        }
    }
}
